2014-01-21 45 views
1

我有一個鏈接,它爲我帶來了一個模式窗口。Rails 4 + Ruby 2中的動態嵌套表單

例子:

link_to "@#{client_name(i)}", 
account_client_path(current_account.id,i.client_id), 
:remote => true, 
class: "client-link", 
"data-toggle" => "modal", "data-target" => "client-dialog-form" 

在此窗口中我想爲這個模型稱爲Issue形式:

class Issue < ActiveRecord::Base 

    before_save { self.number = number.downcase } 

    validate :number,   presence: true, 
          uniqueness: { case_sensitive: false }, 
          length: { maximum: 50 } 

    has_many :items 
    accepts_nested_attributes_for :items 

end 

class Item < ActiveRecord::Base 
    belongs_to :issue 
end 

我的問題是,我希望我的Issue有動態生成的嵌套項目的子窗體。什麼是最好的方式來做到這一點?我在這裏搜索了很多,但都沒有成功。

回答

0

鏈接

可以清理你的鏈接代碼:

link_to "@#{client_name(i)}", account_client_path(current_account.id,i.client_id), :remote => true, class: "client-link", data: {toggle: "modal", target: "client-dialog-form"} 

如果你加載嵌套表格字段,有幾個你必須做的事情才能實現它:

  1. 構建的ActiveRecord對象
  2. 使用fields_for加載對象
  3. 上的手柄形式PARAMS提交

方法如下:

#app/controllers/issues_controller.rb 
def new 
    @issues = Issue.new 
    @issues.items.build # Creates AR object 
end 

def create 
    @issues = Issue.new(issue_params) 
    @issues.save 
end 

private 

def issue_params 
    params.require(:issue).permit(:your, :issue, :params, items_attributes: []) 
end 

#app/views/issues/form.html.erb 
<%= form_for @issue do |f| %> 
    <%= f.text_field :info %> 
    <%= f.fields_for :items do |i| %> 
     <%= i.text_field :info %> 
    <% end %> 
<% end %> 

這將允許你打電話形式&將其附加到您的頁面。由於您的英語(這很好),我無法確定您是否想要即時添加額外的字段。如果你想這樣做,我將不得不爲你寫更多的答案!

讓我知道在評論中!

+0

謝謝,Rich。是的,我確實想通過ajax或某些寶石在飛行中添加額外的字段。我發現迄今爲止稱爲繭的寶石(https://github.com/nathanvda/cocoon)。 – bvlucena

+0

嗨Rich,你是否介意指導我如何在飛行中添加額外的字段?在這種情況下,檢索'item'的html鏈接(單個文本字段名爲info)? –