在Rails中使用SQL命令查找当前用户所在的所有位置。id在字符串中

时间:2022-04-11 19:27:15

In my 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):

在我的应用程序中,有许多文章的贡献者,他们的id存储在数据库中的一个字符串中。我希望找到用户被列为贡献者的文章总数。我在我的应用程序控制器(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".

但是这个代码不能工作。当我做@posts。尺寸,它只提供“0”。

Evironment is Ruby 1.8.6 and Rails 2.3.8

环境是Ruby 1.8.6和Rails 2.3.8

Any thoughts as to how to format the SQL statement?

关于如何格式化SQL语句,您有什么想法吗?

Thanks

谢谢

1 个解决方案

#1


1  

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.

其中%是通配符,表示可以在user_id之前出现任何内容,也可以在用户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:

但是,如果您有机会,我强烈建议建立许多到许多的关系,而不是将id存储在一个字符串中……如:

User
----
id, username, etc 
Posts
--------
post_id, content, etc

Contributors
--------
post_id user_id

#1


1  

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.

其中%是通配符,表示可以在user_id之前出现任何内容,也可以在用户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:

但是,如果您有机会,我强烈建议建立许多到许多的关系,而不是将id存储在一个字符串中……如:

User
----
id, username, etc 
Posts
--------
post_id, content, etc

Contributors
--------
post_id user_id