Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Create/Destroy record in join table

I'm working on this record insert/delete I'm not sure what the syntax is to perform the query.

I have a user model and an event model. I have created a joining table called Personal that stores the user_id, and event_id of any events that the users like.

I created an "Add" method in my events controller so whenever someone clicks it run to that and perform the create logic I'm trying to develop now.The action is tied to a extra column I added to the grid displaying all the events.

The user model =>

 has_many :personals

The event model =>

has_many :personals

The personal model =>

belongs_to :user
belongs_to :events

I thought it would be something like =>

 @user = User.find(session[:user_id])
 @event = Event.find(params[:id])
 # Personal.new = User.Event?

can anyone help?

like image 616
ChrisWesAllen Avatar asked Feb 19 '10 15:02

ChrisWesAllen


People also ask

How do I delete a record from a database in Rails?

Rails Delete operation using delete method Unlike the destroy method, with delete, you can remove a record directly from the database. Any dependencies to other records in the model are not taken into account. The method delete only deletes that one row in the database and nothing else.

How remove data from table in rails?

Rails delete operation using destroy method By using destroy, you can delete the record from rails as well as its other existing dependencies. So in the context of our rails application, if we delete a book record using the destroy function, the authors associated with the book will also be deleted.

What is the difference between delete and destroy in rails?

Basically destroy runs any callbacks on the model while delete doesn't. Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted). Returns the frozen instance.

What is dependent destroy in rails?

Dependent is an option of Rails collection association declaration to cascade the delete action. The :destroy is to cause the associated object to also be destroyed when its owner is destroyed.


1 Answers

If you're using a has_and_belongs_to_many association, which would be unfortunate, removing the associated links can be tricky as there's no identifier for each link.

Using a has_many :through relationship is much easier to maintain and will allow you to do simple things like:

class User < ActiveRecord::Base
  has_many :user_events
  has_many :events,
    :through => :user_events
end

@user.events.delete(@event)

This doesn't remove the Event itself, that'd require an Event#destroy call, but the join record that links the two.

like image 82
tadman Avatar answered Sep 20 '22 04:09

tadman