Ruby on rails ActiveRecord有很多功能
我一直在和很多人斗争:通过关系。假设我有以下表格:Ruby on rails ActiveRecord有很多功能,ruby-on-rails,activerecord,has-many,Ruby On Rails,Activerecord,Has Many,我一直在和很多人斗争:通过关系。假设我有以下表格: Orgs ============== id Integer name String Accounts ============== id Integer name String type Integer org_id Integer Users ==================== id Integer account_id Integer name Strin
Orgs
==============
id Integer
name String
Accounts
==============
id Integer
name String
type Integer
org_id Integer
Users
====================
id Integer
account_id Integer
name String
然后,我按如下方式设置模型:
class Orgs < ActiveRecord::Base
has_many :accounts
has_many :users, through :accounts
class Accounts < ActiveRecord::Base
has_many :users
belongs_to :orgs
class Users < ActiveRecord::Base
belongs_to :accounts
classorgs
如何获取帐户类型为3的Orgs用户(例如)?我应该把条件放在哪里?我不确定您是否想遵循这条路线,但我认为您介绍的模型之间的更好关系如下:
class Orgs < ActiveRecord::Base
has_many :accounts
has_many :users, through: :accounts
class Accounts < ActiveRecord::Base
belongs_to :user
belongs_to :org
class Users < ActiveRecord::Base
has_many :accounts
has_many :orgs, through: :accounts
对于这种情况,您可以使用其他作用域:
class Orgs < ActiveRecord::Base
has_many :accounts
has_many :users, through :accounts
has_many :specific_users, -> { where(accounts: {type: "3"}) }, through: :accounts
classorgs{where(accounts:{type:{3}}}})
有关这方面的更多信息,请参见(4.3.3范围中的has_many)
class Orgs < ActiveRecord::Base
has_many :accounts
has_many :users, through :accounts
has_many :specific_users, -> { where(accounts: {type: "3"}) }, through: :accounts