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.开发者_Python百科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?
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.
精彩评论