2016-04-30 49 views
0

在我的应用程序访问选定的项目,我有以下型号:滑轨属于模拟

# deposit.rb 
class Deposit < ActiveRecord::Base 
end 

# account.rb 
class Accounts < ActiveRecord::Base 
    has_may :payments 
end 

# payment.rb 
class Payment < ActiveRecord::Base 
    belongs_to :account 
end 

在新的模板存款我遍历非常支付属于某个帐户:

# deposits_controller.rb 
class DepositsController < ApplicationController 
    def new 
    @account = Account.find_by(name: "Foo") 
    @payments = @account.payments 
    end 

    def create 
    # i need to access the selected records here 
    end 
end 

# new.html.erb 
<%= form_tag do |f| %> 
    <table class="table"> 
    <thead class="thead-default"> 
     <th> 
     </th> 
     <th>Received From</th> 
     <th>Date</th> 
     <th>Amount</th> 
    </thead> 

    <tbody> 
     <% @payments.each do |p| %> 
     <tr> 
      <td> 
      <%= check_box_tag :selected %> 
      </td> 
      <td><%= number_to_currency(p.amount) %></td> 
     </tr> 
     <% end %> 
    </tbody> 
    </table> 

    <%= submit_tag %> 
<% end %> 

我需要一种方式来访问每个付款,其中selected复选框时提交表单被检查。什么是完成这个最好的方法?

回答

1

使用form_for打造的形式,在这之后,您可以通过复选框的params可变

<% form_for @account, :url => { :action => "update" } do |account_form| %> 
    <% account_form.fields_for : payments do | payments_fields| %> 
    # your checkboxs 
    <% end %> 
<% end %> 
+0

名称访问值也有相匹配的Rails的期望。在允许选择一个或多个名称的情况下,名称应该与末尾具有'[]'的项目[]'相似,以表示“数组”。 – tadman