看起来您基本上是在为has_many :through
关系建模:Item has_and_belongs_to_many User,Rating 是连接模型。您可以阅读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
然后,假设您在数据库中有以下记录:
$ 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
您可以使用以下语句请求所有项目,以及它们相关的 Rating 和 User 实例:
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">], []]