Reputation: 233
Model User
and Article
.
In Article model relationship defined belongs_to :user
. In User model relationship defined has_many :articles
when I trigger below query, gives successful result
Article.select(:name, :id).where(user_id:"fb157fc-a9353453cb95", name:"first")
But when I trigger below query, it gives an error
Article.select(:name, :id).where("user_id (?)","1bf4c2fc-35c37e15d4b5")
Error ActiveRecord::StatementInvalid HINT: No function matches the given name and argument types. You might need to add explicit type casts.
But when I trigger below query, it also gives an error
Article.select(:name, :id).where("articles.user_id (?)","1bf4c2fc-35c37e15d4b5")
Error ActiveRecord::StatementInvalid
Upvotes: 0
Views: 53
Reputation: 7777
Try to the following which tested
@user_id = "fb157fc-a9353453cb95"
@articles = Article.select(:name, :id).where('user_id IN (?)', @user_id)
Hope to help
Upvotes: 0
Reputation: 20253
You're missing =
. Try:
Article.select(:name, :id).where("user_id = (?)","1bf4c2fc-35c37e15d4b5")
I would have thought you would do something more like:
User.find_by(id: "1bf4c2fc-35c37e15d4b5").articles.select(:name, :id)
If you don't need the result to be an ActiveRecord::Relation
containing a collection of Article
instances, you could do:
User.find_by(id: "1bf4c2fc-35c37e15d4b5").articles.pluck(:name, :id)
Which will give you an array
of arrays
. I believe this is a bit faster because you're not instantiating ActiveRecord objects. But, it all depends on what you're needs are.
Upvotes: 0
Reputation: 6531
I think you probably looking for IN
query
so its syntax is: -
user_ids = [1bf4c2fc-35c37e15d4b5,2nd_user_id, 3rd_user_id]
Article.select(:name, :id).where("user_id IN (?)",user_ids)
it will make sql-query like this
SELECT "articles"."name","articles"."id" FROM "articles" WHERE (user_id IN (1bf4c2fc-35c37e15d4b5,2nd_user_id, 3rd_user_id))
if you are looking query for one user_id
in where block then its syntax will be: -
user_id = 1bf4c2fc-35c37e15d4b5
Article.select(:name, :id).where("user_id = ?",user_id)
it will make sql query like this: -
SELECT "articles"."name","articles"."id" FROM "articles" WHERE (user_id =
"1bf4c2fc-35c37e15d4b5")
Hopefully these two above query will make you clear difference between IN with search multiple user_id and for one user_id also.
Upvotes: 2
Reputation: 3095
I believe this is what you're looking for
Article.select(:name, :id).where("user_id =?","1bf4c2fc-35c37e15d4b5")
Active Record will take the first argument as the conditions string and any additional arguments will replace the question marks (?) in it.
Upvotes: 0