简体   繁体   English

Rails 3 - 使用嵌套表单将现有子级添加到父级

[英]Rails 3 - Add existing child to parent with a nested form

My application has a form to update an Event.我的应用程序有一个更新事件的表单。

I'd like to be able to add an existing user to this event with a nested form.我希望能够使用嵌套表单将现有用户添加到此事件中。 I use the Ryan Bates "nested_form" gem.我使用 Ryan Bates “nested_form” gem。

It works great to delete an existing user but how can I add an existing one just with his username?删除现有用户非常有用,但是如何仅使用他的用户名添加现有用户?

Model: Model:

class Event < ActiveRecord::Base
 has_many users
 attr_accessible :users_attributes
 accepts_nested_attributes_for :users, :allow_destroy => true
end

Controller: Controller:

def update
  if @event.update_attributes(params[:event])
   redirect_to @event
  else
   render :edit
  end
end

View:看法:

= f.fields_for :users do |users_form|
  = users_form.text_field :username
  = users_form.link_to_remove "Remove user"
= f.link_to_add "Add a user", :users
= f.submit

Thanks in advance !提前致谢 !

If you want many users coupled to many events, you will need has_many:through relationship.如果您希望许多用户耦合到许多事件,则需要has_many:through关系。 In that case, a relation builds a new row in the database, and in that case it is easier to use the cocoon-gem to dynamically link and unlink pages.在这种情况下,关系会在数据库中构建一个新行,在这种情况下,使用 cocoon-gem 动态链接和取消链接页面会更容易。

I answered a very similar question, also coupling events and users, here .在这里回答了一个非常相似的问题,也是耦合事件和用户。

If you have any more questions, let me know.如果您还有任何问题,请告诉我。

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

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