我目前有以下型号:
class User < ActiveRecord::Base
has_many :locations
has_many :reviews
end
class Location < ActiveRecord::Base
belongs_to :user
has_many :reviews
end
class Review < ActiveRecord::Base
belongs_to :user
end
我希望能够查询 Reviews.where(blah blah),然后按 Location 模型中的列进行过滤。
我有两个问题。 1. 我是否需要更新我的模型才能启用此功能? 2. 如果我改变我的模型,它会破坏我今天在我的数据库中已有的当前记录吗?
我猜这是我需要的更新模型。
class User < ActiveRecord::Base
has_many :locations
has_many :reviews, through: :locations
end
class Location < ActiveRecord::Base
belongs_to :user
has_many :reviews
end
class Review < ActiveRecord::Base
belongs_to :user
belongs_to :location
end
任何关于此的文章或帮助将不胜感激!
最佳答案
你做模型的方式感觉用户拥有位置,我会做不同的:
class User < ActiveRecord::Base
has_many :reviews
has_many :visited_places, through: :reviews, source: :location
end
class Location < ActiveRecord::Base
has_many :reviews
end
class Review < ActiveRecord::Base
belongs_to :location
belongs_to :user
accepts_nested_attributes_for :location, :user
attr_accessible :description, :rank, etc....
end
通过这种方式,用户可以通过评论获得许多地点,您可以说这些地点是他去过的地方。 一个位置可以有很多评论,但当然不属于任何用户。 评论由用户撰写并关注某个地方。
使用此模型,您可以获得给定用户撰写的或与特定位置相关的所有评论,例如 Review.joins(:user).where(username: "toto") 或 Review.joins(:location) .where(location_name: "香港")
关于postgresql - 按关联查询和对模型的影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27557207/