有很多通过两个模型

我有两个重要的模型。 还有更多的模型与它们相互作用,但只有这些模型应该是相关的。

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。

  # has_many :images, through: [:user, :trip] 

使用类似于某些类似方法的数组有时会采用无效语法。

  def images Image.where(user_id: user_id, trip_id: trip_id) end 

我应该这样做吗? 或者有更好的方法吗? 我也试过了has_many上的条件,但是我放在那里的任何动态都被调用了Image::ActiveRecord_Relation

以下是一些示例记录:

           

所以Mission.find(1).images给出了3个图像,而2和3给出了一个空数组。

我想你可以这样试试

 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类的对象,所以我在图像关联上添加了另外一个条件。

 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\" = ?" 

belongs_to关联与另一个模型建立一对一的连接[…]

看起来你可能会让你的图像表有一个mission_id而不是user_idtrip_id因为那时你可以简单地说

  • Image belongs_to Mission
  • 使命has_many图像
  • 用户has_many图像through任务
  • through任务旅行has_many图像