轨道上的多对多关系ruby 3

时间:2011-07-05 13:40:53

标签: ruby-on-rails-3

从下图中。

enter image description here

可以看出我有三个表User,User_group和group。我试图将用户链接到user_group,将Group链接到user_group,换句话说,将用户链接到user_group。目前在我的用户模型中,我有以下内容:

User.rb has_and_belongs_to_many:group

Group.rb has_and_belongs_to_many:用户

我基本上要做的是将数据导入User_group表。解决这个问题的最佳方式是什么?尝试在线搜索,没有运气。

enter image description here

表单布局

用户应该能够将自己分配给一个组。当他们点击更新时,输入的信息应保存到user_group表

1 个答案:

答案 0 :(得分:1)

如果您想使用Rails约定,您应该为表usersgroupsgroups_users命名并更改:

has_and_belongs_to_many :group
has_and_belongs_to_many :user

为:

has_and_belongs_to_many :groups
has_and_belongs_to_many :users

如果您想保留上述表名,则必须执行以下操作:

class User < ActiveRecord::Base
  set_table_name 'USER'
  has_and_belongs_to_many :groups, :join_table => 'USER_GROUP'
end

class Group < ActiveRecord::Base
  set_table_name 'GROUP'
  has_and_belongs_to_many :users, :join_table => 'USER_GROUP'
end

请注意,表名称区分大小写。我使用大写字母,但这可能与你的情况不符。

相关问题