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