2016-04-30 51 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