Rails check_box form to create has_many relationship

时间:2016-03-04 18:21:05

标签: ruby-on-rails checkbox

I have a model called account which has_many :options. I want to create a form in which i can list all the options with a checkbox at the side, so the current account can select the options he/she wants inside a form so I can create the has_many relation.

This is what i have

def index
    @account = current_account
    @options = ['Op 1', 'Op 2', 'Op 3', 'Op 4']
end

and for the view:

 <%= form_for(@account, url: options_path) do |f| %>
    <% @options.each do |op| %>
      <div class="checkbox">
         <%= f.check_box(?????, {:multiple => true}, op, nil) %>
      </div>
    <% end %>
    <%= f.submit class: 'btn btn-default' %>
  <% end %>

This is obviously not working and I'm pretty sure this is not the right way to achieve what I want to do, so any help would be appreciated.

1 个答案:

答案 0 :(得分:0)

您可以使用fields_for:

<%= form_for(@account, url: options_path) do |f| %>
  <%= fields_for :options do |options_form| %>
      <% @options.each do |option| %>
         <div class='checkbox'>
           <%= options_form.label option do %>
               <%= options_form.check_box option %> <%= option %> 
           <% end %>
         </div>
      <% end %>
    <% end %>
    <%= f.submit class: 'btn btn-default' %>
<% end %>

在你的参数中,你会得到如下价值:params[:account][:options]['Op1'],价值为&#39; 1&#39;对于真实和&#39; 0&#39;为假。