在this问题的帮助下,我终于得到了许多关系工作。
不幸的是,因为我正在使用遗留数据库,所以我无法使用默认的rails join方法,因此需要更改列名和字段值。
我有两个模型:raduser和radgroup,它们通过radusergroup加入。以下型号。
我可以使用密钥raduser_id和radgroup_id来使联接工作。我需要做的是分别将这些更改为用户名和组名。
而不是表格如下:
+---------------------------+---------------------------+----------+----+
| raduser_id | radgroup_id | priority | id |
+---------------------------+---------------------------+----------+----+
| 33 | 2 | 1 | 21 |
| 33 | 1 | 1 | 20 |
| 32 | 3 | 1 | 25 |
+---------------------------+---------------------------+----------+----+
我需要它看起来像这样:
+---------------------------+---------------------------+----------+----+
| username | groupname | priority | id |
+---------------------------+---------------------------+----------+----+
| jenny | staff | 1 | 21 |
| steve | sports | 1 | 20 |
| ianw | travel | 1 | 25 |
+---------------------------+---------------------------+----------+----+
我在我的模型中尝试了以下内容,但到目前为止,它都没有成功。
class Raduser < ActiveRecord::Base
has_many :radusergroup, :dependent => :destroy, :primary_key => :groupname, :foreign_key => :username
has_many :radgroup, :through => :radusergroup
end
class Radusergroup < ActiveRecord::Base
belongs_to :raduser, :foreign_key => 'groupname', :primary_key => 'username'
belongs_to :radgroup, :foreign_key => 'username', :primary_key => 'groupname'
end
class Radgroup < ActiveRecord::Base
set_table_name 'radgroup'
has_many :radusergroup, :dependent => :destroy, :primary_key => :groupname, :foreign_key => :username
has_many :raduser, :through => :radusergroup
end
这样做的正确方法是什么?
- 更新 -
表格代码:
- Radgroup.all.each do |radgroup|
= check_box_tag "raduser[radgroup_ids][]", radgroup.id, @raduser.radgroup.include?(radgroup), :id => "raduser_radgroup_id_#{radgroup.id}"
= radgroup.groupname
答案 0 :(得分:2)
您可能不希望在联接表中使用id列:
class CreateRadusergroups < ActiveRecord::Migration
def change
create_table :radusergroups, :id => false do |t|
t.integer :priority
t.string :username, :groupname
end
end
end
以下是设置模型的方法:
class Raduser < ActiveRecord::Base
has_many :radusergroups, :foreign_key => :username
has_many :radgroups, :through => :radusergroups
end
class Radgroup < ActiveRecord::Base
has_many :radusergroups, :foreign_key => :groupname
has_many :radusers, :through => :radusergroups
end
class Radusergroup < ActiveRecord::Base
belongs_to :raduser, :foreign_key => :username
belongs_to :radgroup, :foreign_key => :groupname
end