Ruby on rails 通过多个表获取记录
图中显示了我的部分数据模型。我想通过organizations and items_group获取与用户关联的所有项目。我应该如何更改模型并在控制器中写入此查询?使用:through=>organizations,我可以获取所有项目\组,但我不知道如何包含一个与查询相关项目的关系Ruby on rails 通过多个表获取记录,ruby-on-rails,Ruby On Rails,图中显示了我的部分数据模型。我想通过organizations and items_group获取与用户关联的所有项目。我应该如何更改模型并在控制器中写入此查询?使用:through=>organizations,我可以获取所有项目\组,但我不知道如何包含一个与查询相关项目的关系 class User < ActiveRecord::Base has_and_belongs_to_many :organizations has_many :items_grou
class User < ActiveRecord::Base
has_and_belongs_to_many :organizations
has_many :items_groups, :through => :organizations
end
class Organization < ActiveRecord::Base
has_and_belongs_to_many :users
has_and_belongs_to_many :items_groups
has_many :items, :through => :items_groups
end
class ItemsGroup < ActiveRecord::Base
has_many :items, :inverse_of => :items_group
has_and_belongs_to_many :organizations
has_many :users, :through => :organizations
end
如果您在模型中设置了关系,则该关系应起作用:
users.organizations.item_groups.items
但要使其正常工作,您的模型应包含以下内容:
class User < ActiveRecord::Base
has_many :organizations, :through => :organization_users
end
class Organization < ActiveRecord::Base
has_many :item_groups, :through => :items_groups_organizations
end
class ItemsGroup < ActiveRecord::Base
belongs_to :item
end
希望它对你有用 如果您在模型中设置了这些关系,则应该可以:
users.organizations.item_groups.items
但要使其正常工作,您的模型应包含以下内容:
class User < ActiveRecord::Base
has_many :organizations, :through => :organization_users
end
class Organization < ActiveRecord::Base
has_many :item_groups, :through => :items_groups_organizations
end
class ItemsGroup < ActiveRecord::Base
belongs_to :item
end
希望它对你有用 我认为您可能需要从头开始,然后找到与您的用户连接的项目 您可以在用户类中定义如下方法:
def items
Item.joins(:items_group => {:organizations => :users}).where("users.id" => self.id).select("distinct items.*")
end
由于显式选择,它返回的项目将是只读的,但我认为您希望这样做,以避免多次返回单个项目。我认为您可能必须从头开始,并找到与用户连接的项目 您可以在用户类中定义如下方法:
def items
Item.joins(:items_group => {:organizations => :users}).where("users.id" => self.id).select("distinct items.*")
end
由于显式选择,它返回的项目将是只读的,但我想您会希望这样做,以避免多次返回单个项目。我不认为这样做有效。我认为当您尝试调用组织上的项目组时会出现错误。这对你有用吗?当使用has_和_属于_很多,所以我不需要为关节表创建模型时,我在Rails 3.2.8中得到了这一点:NoMethodError异常:未定义的“items_groups”方法。我不相信这是有效的。我认为当您尝试调用组织上的项目组时会出现错误。这对你有用吗?当使用has_和_属于_很多,所以我不需要为关节表创建模型时,我在Rails 3.2.8中得到了这一点:NoMethodError异常:未定义的方法“items_groups”。