Ordering the first model in association with the second model
I'm working on my first RoR project, and I need to create many, many relationships between two models, but with the ability to order the objects of the first model in association with the second model.
Let's say I have the following two models - Client - Route
I want to assign many clients to many Routes, but with the storage order of this association, for example,
-Route 1
--Customer 2, position 1
--Customer 1, position 2
-Route 2
--Customer 3, position 1
--Customer 1, position 2
I think I need to use has_many: through and owned_to and creat "position" on the in-middle-table for this, but then how do I make this field available and editable?
source to share
You can 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 order model will save the date / position and you can access it:
c = Customer.first
c.routes(:include => :bookings, :order => "bookings.position")
source to share
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 boring for a long time, but you should get the idea.
source to share
I want to display all clients assigned to one route, so the query sent to the database is:
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 second query does not contain enough information in the WHERE calus as it fetches information for all routes for specific clients, not just specific clients for a specific route (id = 1).
.. is RoR doing additional filtering after retrieving this data?
by the way. I have: include =>: booking added to route model
source to share