它看起來像你基本上建模一個has_many :through
關係:項目has_and_belongs_to_many用戶和評級是聯接模型。您可以在Rails Guide to Active Record Associations中閱讀關於:through
關係。
如果是這樣的話,我會建議使用has_many :through
如下構建模型的關係:
class Rating < ActiveRecord::Base
attr_accessible :item_id, :user_id
belongs_to :item
belongs_to :user
end
class User < ActiveRecord::Base
has_many :ratings
has_many :rated_items, :through => :ratings
end
class Item < ActiveRecord::Base
has_many :ratings
has_many :rated_by_users, :through => :ratings, :source => :user
end
然後,說你有在DB以下記錄:
$ sqlite3 db/development.sqlite3 'SELECT * FROM items';
1|2013-03-22 03:21:31.264545|2013-03-22 03:21:31.264545
2|2013-03-22 03:24:01.703418|2013-03-22 03:24:01.703418
$ sqlite3 db/development.sqlite3 'SELECT * FROM users';
1|2013-03-22 03:21:28.029502|2013-03-22 03:21:28.029502
$ sqlite3 db/development.sqlite3 'SELECT * FROM ratings';
1|1|1|2013-03-22 03:22:01.730235|2013-03-22 03:22:01.730235
你可以要求的項目,與他們相關的評分和用戶實例,一起這樣的說法:
items = Item.includes(:rated_by_users)
此執行3個您的SQL查詢:
Item Load (0.1ms) SELECT "items".* FROM "items"
Rating Load (0.2ms) SELECT "ratings".* FROM "ratings" WHERE "ratings"."item_id" IN (1, 2)
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" IN (1)
,並試圖訪問用戶(一個或多個),其額定每個項目可以通過調用每個項目的#rated_by_users
聯想法來完成:
> items.map {|item| item.rated_by_users }
=> [[#<User id: 1, created_at: "2013-03-22 03:21:28", updated_at: "2013-03-22 03:21:28">], []]
檢查此鏈接。 http://stackoverflow.com/questions/4197418/rails-3-eager-loading-with-conditions – 2013-03-21 08:57:42
請包括用戶模型 – gabrielhilal 2013-03-21 09:08:23
@AbibullahRahamathulah這個問題是關於靜態參數(has_many條件),而不是動態的 – thejaz 2013-03-21 09:16:15