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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With