update values of checkbox with HABTM relationship — Rails

前端 未结 2 1085
旧巷少年郎
旧巷少年郎 2021-01-07 10:56

Hey guys I\'ve been using the has_and_belongs_to_many relationship with checkboxes example from the Railscast Episode #17 . I had some problems and now everything is workin

相关标签:
2条回答
  • 2021-01-07 11:43

    The check_box tag must look like this for it to work:

    <%= check_box "user", "user_interest_ids", {:checked => @user.interests.include?(interest), :name => 'user[interest_ids][]'}, interest.id, nil %>
    

    In my ad <-> ad_sizes habtm relationship I'm using this code:

    <% @ad_sizes.each do |s| %>
    <li>
    <%= check_box "ad", "ad_size_ids", {:checked => @ad.ad_sizes.include?(s), :id => "ad_size_#{s.name}", :class => 'checkbox', :name => 'ad[ad_size_ids][]'}, s.id, nil %>
    <label class="checkbox" for="<%= "ad_size_#{s.name}" %>"><%= s.description %></label>
    </li>
    <% end %>
    
    0 讨论(0)
  • 2021-01-07 11:44

    I played around with the form and the correct code is this ==>

    <% form_for @user do |f| %>
    <% for interest in Interest.find(:all) %>
    <div>
     <%= check_box_tag "user[interest_ids][]", interest.id, @user.interests.include?(interest) %>
     <%= interest.name %>
    </div>
    <% end %>
    <p>
    <%= f.submit 'Edit' %>
    </p>
    <% end %>
    

    I'm so happy! So apparently the problem was :user which should the be object @user.

    0 讨论(0)
提交回复
热议问题