How do I see tags for all users on a model instance?
I am using acts-as-taggable on. Two models: User and Posts.
Posts belongs_to :user
User has_many :posts
Posts acts-as-taggable. Users acts-as-tagger
All of this is straightforward and is working. However, I have a use-case which may be outside of how this plugin works.
I want Posts to be able to be tagged by multiple users. When a tag is created on a post from a user, it does not show when you do the following:
p = Post.first
p.tag_list # this returns []
If you look at the SQL being generated it selects records where 'tagger_id' is NULL. The tagger_id is, of course, the user_id in this case and开发者_如何学Python is very much not NULL.
If you back into it, however, you can get what you want.
p = Post.find(1) # get a post to work with
p.tags_from(p.user) # returns an array of the tags: ['cats','dogs','wildebeasts']
This works.
Now, the problem is I want another user to be able to come along and add a tag to the post. Maybe this user will think it is helpful. Let's just assume it makes sense to do so. Could be a moderator... whatever.
Given the above, how would I get a list of all the tags on a given post assuming that more than one user added tags?
Gratefully,
NJ
I don't know anything about the plug-in you specified and I'm still learning Rails. But I don't think
p = Post.tag_list
would be what you want, anyways. You're asking for a taglist of the Post class rather than the taglist of a particular post. For example, if users have 'email' and 'name' columns, you also couldn't do:
u = User.names
u = User.emails
It doesn't really make sense. But you could do something like:
User.column_names
#=> ["id", "email", "hashed_password", "created_at", "updated_at"]
Because that's a class method. Now, maybe tag_list is a class method, but it looks like it's used to find orphaned tags or something due to how it looks for null tag_givers.
But since I'm still new to Rails and I also don't know how your plugin works, here are some things you can try off the top of my head:
p = Post.find(1)
p.tag_list # p.column_name_of_the_column_that_holds_the_tags should work
# or, maybe pass in ALL users as an array
p.tags_from(User.all)
Lemme know what those do.
Maybe I'm missing something but:
p = Post.tag_list # this returns []
#should be
#...
@post.find params[:id]
#...
@post.tag_list
You're currently calling tag_list on the post class, rather than an instance of it.
精彩评论