简体   繁体   中英

rails adding tags to controller

I am implementing a basic tagging feature to my app. New to rails.

I have a listings model and I am working in the listings_controller # index. When the user goes to the listing page and sets the :tag param I want @users only to hold the users which match the tag.

So if they goto www.example.com/listings?tag=foo only pages which have been tagged with foo are loaded. This is what I have come up with so far but there is several problems with it.

def index
  if params[:tag]
    @id = Tag.where(:name => params[:tag]).first.id
    @listingid = Tagging.where(:tag_id => @id) 

    @listingid.each do |l|
      @users = User.find(l.listing_id)
    end
  else
    @users = User.all
  end
end

I am not sure how to loop and add each found user to @users. I think I may be going about this whole thing the wrong way.. My tag/tagging models look as follows:

tag.rb

class Tag < ActiveRecord::Base
    has_many :taggings
    has_many :listings, through: :taggings
end

tagging.rb

class Tagging < ActiveRecord::Base
  belongs_to :tag
  belongs_to :listing
end

Taggings has the following colums:

id, tag_id, listing_id

Tags has the following columns:

id, name

Any guidance would be appreciated, been trying to fix this for a while with no luck.

Trying with

def index
  @tag = Tag.where(:name => params[:tag]).first
  if @tag
    @listings = @tag.listings.includes(:user)
    @users = @listings.map{|l| l.user}
  else
    @users = User.all
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM