Ordering First Model in Association with Second Model

守給你的承諾、 提交于 2019-12-04 16:55:12

You could go with :through:

class Route < ActiveRecord::Base
  has_many :bookings
  has_many :routes, :through => bookings
end

class Booking < ActiveRecord::Base
  belongs_to :route
  belongs_to :customer
end

class Customer < ActiveRecord::Base
  has_many :bookings
  has_many :routes, through => :bookings
end

Your Bookings model would keep the date/position and you could access them with:

c = Customer.first
c.routes(:include => :bookings, :order => "bookings.position")
class Customer < ActiveRecord::Base
  has_many :routes, :through => :trips
  ...
end

class Trip < ActiveRecord::Base
  belongs_to :customer
  belongs_to :route
  // has a ordinal called 'seq'
  ...
end

class Route < ActiveRecord::Base
  has_many :customers, :through => :trips
  ...
end

You should be able to access the ordinal field via @customer.routes[0].seq I haven't tested it and my rails skills are long dull but you should get the idea.

cite's solution is right. to access the middle table, try:

c.bookings # this will return the 'middle table' which then you have the access to the positions 
c.bookings.first.position

I want to display all customers assignes to one routes, so the query sent to database are:

SELECT customers.* FROM customers INNER JOIN bookings ON customers.id = bookings.customer_id WHERE ((bookings.route_id = 1))

and then

SELECT bookings.* FROM bookings WHERE (bookings.customer_id IN (1,2,3))

..so, the 2nd query does not contain enought information in WHERE calus, because it's selecting information for all routes for specific customers, not just about specific customers for specific route (id=1).

..is RoR doing some extra filtering after fetching this data?

btw. I have :include => :bookings added into Route model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!