有很多通过两个模型
我有两个重要的模型。 还有更多的模型与它们相互作用,但只有这些模型应该是相关的。
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_id
和trip_id
因为那时你可以简单地说
- Image
belongs_to
Mission- 使命
has_many
图像- 用户
has_many
图像through
任务through
任务旅行has_many
图像
- Geocoder Gem:如何在两种不同型号之间使用?
- 选择的选择轨道错误不是一个function
- Rails – 了解application.js和application.css
- 当使用Proc.new v。&符号时,为什么ruby中的break语句表现不同?
- Rails和MySQL – ActiveRecord :: ConnectionNotEstablished在生产环境中
- validation与模型的错误消息相关联
- Heroku错误:ActionView :: Template :: Error(未定义的方法`validation码’用于#)
- 以简单forms手动设置表单输入字段的ID?
- 连接被拒绝 – 在Mongodb上使用rake db:seed连接(2)