问题描述
我在这里有两个重要的模型.还有更多与之交互的模型,但只有这些模型才有意义.
I have two models of importance here. There's more models interacting with them too, but only these should be relevant.
class Image < ActiveRecord::Base
belongs_to :user
belongs_to :trip
end
class Mission < ActiveRecord::Base
belongs_to :user
belongs_to :trip
# has_many :images, through: :user
end
已注释掉的行将我带到一半,但我想满足图像具有与任务相同的旅程ID的其他条件.
The commented out line gets me halfway there but I want to meet an additional condition of the image having the same Trip ID as the Mission.
# has_many :images, through: [:user, :trip]
像某些类似方法有时使用数组那样,这是无效的语法.
Using an array like some similar methods sometimes take, is invalid syntax.
def images
Image.where(user_id: user_id, trip_id: trip_id)
end
我应该那样做吗?还是有更好的方法呢?我还在has_many上尝试了条件语句,但是我放置的任何动态变量都被Image::ActiveRecord_Relation
Should I just do that? Or is there a better way to do it? I also tried with conditionals on the has_many but anything dynamic I put there was being called off of Image::ActiveRecord_Relation
以下是一些示例记录:
<User id=1>
<User id=2>
<Trip id=1>
<Trip id=2>
<Image id=1, user_id=1, trip_id=1>
<Image id=2, user_id=1, trip_id=1>
<Image id=3, user_id=1, trip_id=1>
<Mission id=1, user_id=1, trip_id=1>
<Mission id=2, user_id=2, trip_id=1>
<Mission id=3, user_id=2, trip_id=2>
所以Mission.find(1).images
返回3张图像,而2和3返回一个空数组.
So Mission.find(1).images
gives back the 3 images, whereas 2 and 3 give an empty array.
推荐答案
我认为您可以尝试
class Mission < ActiveRecord::Base
belongs_to :user
belongs_to :trip
has_many :images, ->(obj) { where("#{Image.quoted_table_name}.trip_id = ?", obj.trip_id)}, through: :user
# or
has_many :images, ->(obj) { where("#{Image.quoted_table_name}.user_id = ?", obj.trip_id)}, through: :trip
end
此obj代表Mission类的对象,因此我在图像关联上添加了一个条件.
This obj represents the object of Mission class, so i have added the one more condition on images associations.
Mission.first.images.to_sql
#=> "SELECT \"images\".* FROM \"images\" INNER JOIN \"users\" ON \"images\".\"user_id\" = \"users\".\"id\" WHERE (\"images\".trip_id = 1) AND \"users\".\"id\" = ?"
这篇关于具有多点穿越两种模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!