简体   繁体   English

rails-在连接表中创建记录

[英]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. 我使用HABTM关系,因为我真的不需要任何额外的字段。

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] 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 => 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.... 和btn_link看起来像....

<% @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 = uecreate ????? x = uecreate ?????

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 . INSTEAD:你应该写测试 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. 当然,你最好在测试中使用factory_girl + shoulda。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM