Rails 4 - checkboxes for has_and_belongs_to_many association

后端 未结 3 2030
悲&欢浪女
悲&欢浪女 2020-12-01 12:29

I recently had a problem getting checkboxes to work for a has_and_belongs_to_many (HABTM) association in Rails 4. I was able to find the information on how to get it working

3条回答
  •  一向
    一向 (楼主)
    2020-12-01 13:18

    I implement has_and_belongs_to_many association this way:

    model/role

    class Role < ActiveRecord::Base
      has_and_belongs_to_many :users
    end
    

    model/user

    class User < ActiveRecord::Base
      has_and_belongs_to_many :roles
    end
    

    users/_form.html.erb

    ---
    ----
    -----
     
    <% for role in Role.all %>
    <%= check_box_tag "user[role_ids][]", role.id, @user.roles.include?(role) %> <%= role.name %>
    <% end %>

    users_controller.rb

    def user_params
        params.require(:user).permit(:name, :email, { role_ids:[] })
      end
    

    Intermediate table_name should be roles_users and there should be two fields:

    1. role_id
    2. user_id

提交回复
热议问题