In m开发者_StackOverflowy app, there are a number of contributors to a post, with their id's stored in a string in the database. I'd like to find the total of posts where the user is listed as a contributor. I've put the following in my ApplicationController (before_filter'ed):
@posts = Post.find :all, :conditions => ['contributors like ?', current_user.id]
That code isn't working though. When I do @posts.size, it only offers up "0".
Evironment is Ruby 1.8.6 and Rails 2.3.8
Any thoughts as to how to format the SQL statement?
Thanks
You want something like:
@posts = Post.find :all, :conditions => ["contributors like '%?%'", current_user.id]
Where %
is a wildcard saying that anything can come before the user_id and anything can come after the user id.
However if you have the chance, I'd highly suggest making a many to many relationship instead of storing the id's in a string... such as:
User
----
id, username, etc
Posts
--------
post_id, content, etc
Contributors
--------
post_id user_id
精彩评论