开发者

rails- creating record in a join table

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_t开发者_如何学Goo :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 ?????


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


But I'm not sure how to check to see if its working

You can check it in console, but it does not prove it will always work. It will prove it has worked in your case. Next time you want to test one simple case you should again go to console.

INSTEAD: You should write tests. For example:

def test_add_events_for_user
  u = users(:some_user)
  e1, e2 = events(:one), events(:two)
  post :add_event, user => {u.id, :event_ids => [e1.id, e2.id] }
  assert u.events.include?(e1)
  assert u.events.include?(e2)
end

And of course you'd better use factory_girl + shoulda in your tests.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜