开发者

Many to Many AND habtm-checkboxes help needed!

For some reason nothing is getting stored in my groups_user table below is the info.

My Models

group.rb

class Group < ActiveRecord::Base
  has_and_belongs_to_many :users
end

user.rb

class User < ActiveRecord::Base
  has_and_belongs_to_many :groups
end

groups_user.rb

class GroupsUser < ActiveRecord::Base
end

The Entity Relationship Diagram

http://i.imgur.com/MqWok.png

The Form

http://i.imgur.com/BwwaV.png

The view code

<% for group in @groups %>
    <%= check_box_tag "user[group_ids][]", group.id, @user.gr开发者_开发百科oups.include?(group) %>
    <%= group.description %>
    <% end %>

users_controller.rb

def update 
  @user = User.find(params[:id]) 
  params[:user][:group_ids] ||= [] 
  if @user.update_attributes(params[:user]) flash[:success] = "User updated." 
    redirect_to @user #end 
  else 
    @title = "Edit user" 
    render 'edit' 
  end 
end


i had the same problem and it take my head blowing off:

The solution for me was simply adding this into my User Model (app/models/user.rb)

class User < ActiveRecord::Base
    attr_accessible :group_ids
    [...]
end

Hope this helps!


it should be groups_users not groups_user and you don't have to create model for this table

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜