jriff
jriff

Reputation: 1977

Has many conditions in Rails 4

How to do this:

 has_many :space_mappings, -> { where(group_id: group_id) }, through: :category

That is - SpaceMapping and this model both has a group_id and they have to match. I could just make a method but I would like for this to be possible.

Here I get:

undefined local variable or method `group_id' for #<ActiveRecord::Relation::ActiveRecord_Relation_SpaceMapping:0x007fe5ac118bd8>

I have done this instead:

def space_mappings
  category.space_mappings.where(space_id: Space.where(group_id: group_id))
end

Thanks in advance.

Upvotes: 0

Views: 202

Answers (2)

gregates
gregates

Reputation: 6714

If "this model" has a belongs_to :category relationship or a has_one :category relationship, then you shouldn't need that where clause at all. The whole point of "has many through" is to restrict the associated models to those that are associated with the model they're associated through

That is, you should just be able to do

belongs_to :category
has_many :space_mappings, through: :category

assuming that space mappings also belong to a category.

Upvotes: 1

Tauhidul Islam
Tauhidul Islam

Reputation: 376

You must assign a value for category_id.

See http://guides.rubyonrails.org/association_basics.html (4.3.3.1 section). It can help your for understanding details and clear concept.

Upvotes: 1

Related Questions