[英]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. 我有一个列表模型,并且正在使用listings_controller#索引。 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. 当用户转到列表页面并设置:tag参数时,我只希望@users保留与标签匹配的用户。
So if they goto www.example.com/listings?tag=foo only pages which have been tagged with foo are loaded. 因此,如果它们转到www.example.com/listings?tag=foo,则只会加载已用foo标记的页面。 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. 我不确定如何循环并将每个找到的用户添加到@users。 I think I may be going about this whole thing the wrong way.. My tag/tagging models look as follows: 我认为我可能会以错误的方式处理整件事。我的标记/标记模型如下所示:
tag.rb tag.rb
class Tag < ActiveRecord::Base
has_many :taggings
has_many :listings, through: :taggings
end
tagging.rb 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.