开发者

Rails: has_many :through _ids nested?

开发者 https://www.devze.com 2023-03-02 22:18 出处:网络
On a single page I might have a single Video and then checkboxes to add multiple dogs to it. Easy enough (as follows)...

On a single page I might have a single Video and then checkboxes to add multiple dogs to it. Easy enough (as follows)...

View:

<%= check_box_tag "video[dog_ids][]", dog.id %>

Controller:

params[:video][:dog_ids] ||= []  

But what I can't figure out how to do is have multiple videos, each with multiple dogs.

I currently have this:

<% @videos.each do |video| %>
  <%= fields_for "item[]", video do |f| %>
    <%= f.hidden_field :id, :index => nil %>
    <%= 开发者_Python百科f.text_field :title, :index => nil%>
    <%= f.text_area :body, :index => nil %>

    <% video.dogs.each do |dog| %>
      <%= check_box_tag "item[][video[dog_ids][]]", dog.id %>
    <% end %>
  <% end %>
<% end %>

But when I do that, dogs_ids is always nil when it's submitted.

Any idea what I'm doing wrong?


Such a setup with fields_for "item[]" and f.text_field :title, :index => nil produces:

<input id="item__name" name="item[][title]" size="30" type="text" value="vid1">

This indicates that the checkbox name should be item[][dog_ids][]. A working example:

<% @videos.each do |video| %>
  <%= fields_for "item[]", video do |f| %>
    <%= f.text_field :title, :index => nil %>
    <% video.dogs.each do |dog| %>
      <%= check_box_tag "item[][dog_ids][]", dog.id %> <%= Dog.name %>
    <% end %>
    <br>
  <% end %>
<% end %>

This produces result in params:

{"item"=> [
  {"title"=>"vid1", "dog_ids"=>["1", "2"]},
  {"title"=>"vid2", "dog_ids"=>["2"]},
  {"title"=>"vid3", "dog_ids"=>["2", "3"]}
]}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号