使用 Rails 3.2.9
我试图获取与没有所有者的组织相关联的项目列表。
我能够使用下面的方法获得一个数组列表,但对我来说似乎很难看。有一个更好的方法吗?
Items.all(:select => "items.id, items.name",
:joins => "INNER JOIN organizations on items.organization_id = organizations.id",
:conditions => "NOT EXISTS (select * from items k JOIN items_owners on items.id = items_owners.item_id) and items.organization_id = 1")
表设置:
所有者:
- ID
- 姓名
项目:
- ID
- 姓名
- 组织 ID
物品所有者:
- owner_id
- item_id
组织:
- ID
- 项目清单
楷模:
class Organization < ActiveRecord::Base
attr_accessible :name
has_many :items
end
class Item < ActiveRecord::Base
attr_accessible :description, :name, :owner_ids, :organization_id
has_many :items_owner
has_many :owners, :through => :items_owner
belongs_to :organization
end
class Owner < ActiveRecord::Base
attr_accessible :name
has_many :items_owner
has_many :items, :through => :items_owner
end
class ItemsOwner < ActiveRecord::Base
attr_accessible :owner_id, :item_id
belongs_to :item
belongs_to :owner
end