Nested has_many: through rails 3

I know that Rails does not support nested has_many: through relationships, although there has been talk and an open ticket about the patch since Rails 2.

I came through a plugin that was pretty smooth, but the main branches do not work with Rails 3, and I hesitate to use this for mission critical tasks in the application, hence the lack of recent active development. So what is the best way to deal with this relationship.

class Author < ActiveRecord::Base has_many :contracts has_many :products, :through => :contracts class Product < ActiveRecord::Base has_many :contracts has_many :orders has_many :authors, :through => :contracts class Contracts < ActiveRecord::Base belongs_to :author belongs_to :product 

So, all the creatures, which would be great, could get when ordering, adding this to the author’s model:

 has_many :orders, :through => :products 

But alas, you cannot - at least without a plugin. So my question is, what is the best approach to access all copyright orders, when is the only association between the connection model, Contracts?

+4
source share
3 answers

If you are not trying to create objects through a nested relationship, and want to use them only for searching, then Rails 3 scopes are a great way to do this. Alternatively, you can implement a class method.

I had such a thing as an example in a class I taught recently, the Rails 3 code version is here: https://github.com/wolframarnold/Efficient-TDD-Rails3/blob/master/app/models/user.rb

See the definition of the items method. Specifications here: https://github.com/wolframarnold/Efficient-TDD-Rails3/blob/master/spec/models/user_orders_spec.rb

Rails 3.1 Update. As one commenter has already pointed out, Rails 3.1 supports has_many: through associations of more than one level.

+8
source

As I can see, you have 2 options:

  • You may need to rethink your modeling decisions. For example, establish a many-to-many relationship between the Customer and the Product through an order. And then incubate the contract.

  • Use a named scope (or scope in Rails 3) to retrieve copyright orders.

If clicked, I would enable option 1.

+1
source

The ticket does not seem to be active anymore to include the patch in the Rails core. I would introduce it ... it looks like it should be something that should only work in Rails.

+1
source

Source: https://habr.com/ru/post/1335934/


All Articles