0

this is my house model

has_many :taggings
has_many :tags, through: :taggings

def self.tagged_with(name)
    Tag.find_by_name!(name).houses
 end

end

this is my house controller

    def index
        if params[:tag]
          @houses = House.tagged_with(params[:tag])
    end
end

view:

- @houses.each do |house|
ect

This works fine...this filters out the houses with the current tag, like this /house/tag/tagname

But i implemented a nested resources so i need to change my view to this.

- @regions.each do |region|
      - region.houses.find_all do |house|

How can i use the filter tag in the new view? I thought this

- @regions.each do |region|
      - region.houses.find_tagged_with(params[:tags]) do |house|

but this wil not work...please help.

2 Answers 2

1

Why not filter it the other way around? That is, instead of getting all the houses for a region and filtering it by tag, get all the houses for a tag and filter it by region:

def index
  @regions = Region.all # or whatever
  @houses = House.tagged_with(params[:tag])

  @regions.each do |region|
    @houses.where(region_id: region.id).each do |house|
      ...
    end
  end
end
Sign up to request clarification or add additional context in comments.

Comments

0

This will not work becoz the tagged_with is defined in the class House and is not callable on the instance or any collection. The region.houses is an array (assuming region has_many houses) so it won't work on it. One way to do this is to use ActiveRecord::Relation

@regions.each do |region|
 - region.houses.where(:name => params[:tag).each do |house|

Refer to Rails guide to know more about it...

1 Comment

thanks Aditya for the quick reply!. I test you're your solution but my output is null. I think because the tags is in an another table. class House < ActiveRecord::Base extend FriendlyId has_many :taggings end class Tag < ActiveRecord::Base has_many :houses, through: :taggings end How can i solve this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.