João Daniel
João Daniel

Reputation: 8986

Association belongs_to :through

I know that isn't any belongs_to :through association in Rails, but how could I work around it?

I want to create an association stating that a Forecast belongs to a User. However, I understand that since a Forecast already belongs to a User, it shouldn't be necessary to store used_id inside Forecast model.

How can I create this relationship between Forecast and User through the Batch model?

EDIT

Let me better explain my problem.

I have the following models and associations:

User < ActiveRecord::Base
  has_many :batches
# has_many :forecasts, through: :batches
end

Batch < ActiveRecord::Base
  belongs_to :user
  has_many :forecasts
end

Forecast < ActiveRecord::Base
  belongs_to :batch
# belongs_to :user, through: :batch
end

The commented lines is what I want to do, but I cannot, since there is no belongs_to :through association.

The relationship is strictly what is said on the code: a User may have many batches. A batch is a set of forecasts, so a Batch may have many forecasts. Since a Batch must belong to a User, and a Forecast must belong to a Batch, then a Forecast belongs to a User.

I want to get select all Forecasts that belongs to all Batches from a User.

current_user.forecasts

The reason I want to do that, is to limit the scope of a user only to its own batches and forecasts. So on controller actions, instead of

Batch.find(params[:id])

or

Forecast.find(params[:id])

I can make

current_user.batches.find(params[:id])

or

current_user.forecasts.find(params[:id])

It is already possible to do that with Batch. Forecasts, on the other hand, doesn't belongs_to a user yet. How can I do that?

Upvotes: 0

Views: 278

Answers (2)

sockmonk
sockmonk

Reputation: 4255

In your User model:

has_many :batches
has_many :forecasts, :through => :batches

In your Batches model:

belongs_to :user
belongs_to :forecasts

In your Forecasts model:

has_many :batches has_many :users, :through => :batches

That last line is just if you want the relationship to go both ways, like a full many-to-many relationship.

Upvotes: 0

Veraticus
Veraticus

Reputation: 16084

There is has_many :through in Rails. You can check out the Rails guide to see how to use it.

Upvotes: 1

Related Questions