James
James

Reputation: 1887

Rails access selected items that belong to model

In my application I have the following models:

# 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

In the new template for deposits I am looping over very payment that belongs to a certain account:

# 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 %>

I need a way to access each payment where the selected checkbox is checked when the form is submitted. What is the best way to accomplish this?

Upvotes: 0

Views: 47

Answers (1)

felipecamposclarke
felipecamposclarke

Reputation: 924

Use form_for to build the form, after that, you can access the values through the params variable

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

Upvotes: 1

Related Questions