2011-06-09 92 views
1

我的應用程序有一個用於更新事件的窗體。Rails 3 - 將現有的子項添加到嵌套表單的父項

我希望能夠以嵌套的形式添加一個現有的用戶到這個事件。 我使用Ryan Bates「nested_form」gem。

它很好地刪除現有的用戶,但我怎麼才能用他的用戶名添加一個現有的用戶?

型號:

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

控制器:

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

查看:

= 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 

提前感謝!

+0

用戶只能鏈接到一個事件嗎? – nathanvda 2011-06-09 13:27:18

+0

用戶可以鏈接到多個事件:) – invaino 2011-06-09 15:36:38

+0

我看着你的繭寶石令人印象深刻,但我沒有找到一種方法來添加一個現有的孩子 – invaino 2011-06-09 15:49:53

回答

1

如果你想讓很多用戶加入到很多活動中,你將需要has_many :through關係。在這種情況下,關係會在數據庫中建立一個新行,在這種情況下,使用cocoon-gem動態鏈接和取消鏈接頁面會更容易。

我回答了一個非常類似的問題,也耦合事件和用戶,here

如果您還有其他問題,請告訴我。

相關問題