54305

Has Many Through two models

Question:

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

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

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

Here are some sample records:

<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>

So Mission.find(1).images gives back the 3 images, whereas 2 and 3 give an empty array.

Answer1:

I think you can try like this

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

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

Answer2:

<blockquote>

A belongs_to association sets up a one-to-one connection with another model [...]

</blockquote>

It looks like you could benefit making your image table have a mission_id instead of user_id and trip_id since then you could simply say

<blockquote> <ul><li>Image belongs_to Mission</li> <li>Mission has_many Images</li> <li>User has_many Images through Mission</li> <li>Trip has_many Images through Mission</li> </ul></blockquote>

Recommend

  • Two columns in Winforms RichTextBox
  • Rounding in numpy?
  • how do I design intermittent via points for travel itinerary
  • How to move the later half of a vector into another vector?
  • Bing Map polyline using MVVM pattern XAML
  • query large table
  • count(*) cannot be selected in PL/SQL
  • Streaming video file?
  • How to change slowly background attributes in jquery?
  • Python error: len() of unsized object while using statsmodels with one row of data
  • MySpace DOM?
  • CakePHP Subquery from SQL
  • jQuery: click function bind in for-loop with closure fix
  • overlapping appointments using the entity framework
  • ggplot2 polygon world map centred with limits gives funny edges
  • Where in the relevant specification is it documented that some comments in a SQL script are, in fact
  • ckeditor and jquery UI dialog not working
  • Most efficient way to move table rows from one table to another
  • std::remove_copy_if_ valgrind bytes in block are possibly lost in loss record
  • How does document.ready work with angular element directives?
  • presentShareDialogWithParams posts to FB wall, but callback handler results say error
  • How can I enlarge video fullscreen without the affected interface project in as3?
  • Grails calculated field in SQL
  • How to write order and limit within cakephp joins array
  • Python urlparse: small issue
  • FileReader+canvas image loading problem
  • Lost migrations and Azure database is now out of sync
  • Using $this when not in object context
  • How do I fake an specific browser client when using Java's Net library?
  • How reduce the height of an mschart by breaking up the y-axis
  • How to add date and time under each post in guestbook in google app engine
  • MySQL WHERE-condition in procedure ignored
  • Perl system calls when running as another user using sudo
  • JSON with duplicate key names losing information when parsed
  • Return words with double consecutive letters
  • How to delete a row from a dynamic generate table using jquery?
  • json Serialization in asp
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • How to stop GridView from loading again when I press back button?
  • python draw pie shapes with colour filled