rails- creating record in a join table

join, ruby-on-rails

Solution

Try this:

u = User.find(1)
u.events << Event.find(1) # will add the Event object to the user events

u.events.last # will show the event added

Problem

I'm trying to create a record within a join table from the action of a button. To explain, I would have an events model and would like to track selected events from each user. I used the HABTM relationship since I dont really need any extra fields. User.rb => has_to_and_belongs_to_many :events Event.rb => has_to_and_belongs_to_many :users Events_Users Migration => [user_id, event_id, id=>false] So how I thought I would do it is.... users_controller.rb => ``` def add_event @user = User.find(session[:user_id]) params[:user][:event_ids] ||= [] if @user.update_attributes(params[:user]) flash[:notice]='Added to My Events' redirect_to :action => "index" end end ``` and the btn_link looks like.... ``` <% @events.each do |event| %> <%= link_to image_tag("heart.gif"), :controller => 'user', :action => 'add_event' %> <%=h event.name %> <%=h event.description %> <% end %> ``` But I'm not sure how to check to see if its working...How would I perform these action in the console so I can check if the records being added? ``` u = User.find(1) e = Event.find(1) ``` ????? x = u.e.create ?????

Original source