Search code examples
ruby-on-railsruby-on-rails-3controllerform-forfields-for

How to Handle 2 tables with one form_tag? Rails 3


  1. Beneficiaries
    • id (PK)
    • name
    • age
    • income
  2. Beneficiary_loans
    • id (PK)
    • beneficiary_id (FK)
    • amount
    • rate
    • period

What I'm doing is, selecting a list of beneficiary from [Beneficiaries] table and displaying as follows

<%= form_tag({:action => 'update_survey_list_status', :status=>4}) do %>
  <table width="100%">
    <tr>
      <th>Beneficiary Details</th>
      <th>Amount</th>
      <th>Rate</th>
      <th>Period</th><th>
      <input type='checkbox' name='checkall' onclick='checkedAll();'>
      </th>
    </tr>
    <% @publishedlist.each do |b| %>
    <tr>
      <td><%= b.firstname %></td>
      <%= fields_for :beneficiaryloan do |bloan| %> 
        <td> <%= bloan.text_field :amount%></td>
    <td> <%= bloan.text_field :rate%></td>
    <td> <%= bloan.text_field :period%></td>
      <% end %> 
     <td><%= check_box_tag "benificiary_ids[]",b.id, :name => "benificiary_ids[]"%>     </td>
   </tr>
   <% end %>
  </table> <%= submit_tag "Approve", :class=>'form_buttons'  %>
<% end %>

In controller,

@beneficiaries=Beneficiary.find(:all, :conditions => ["id IN (?)",     params[:benificiary_ids]])  
@beneficiaries.each do |b|
    @beneficiaryloan = Beneficiaryloan.new(params[:beneficiaryloan])
    @beneficiaryloan.beneficiary_id=b.id
    @beneficiaryloan.hfi_id=session[:id].to_s
    @beneficiaryloan.status_id=params[:status]
    @beneficiaryloan.save
end

What I'm not getting is

params[:beneficiaryloan]

Values are coming as NULL Am I missing something here in this form?


Solution

  • Check the following,

    1. With the help of any browser tool(eg:firebug), make sure that the form has been rendered properly. Sometimes due to some misplaced tags(generally happens with table structure) the form does not renders properly.
    2. Try to remove the table structure and see if the form works.
    3. Make sure your association is fine, i guess it should be Beneficiary has many Beneficiaryloan

    If none of the above helps, please post the request parameters over here.