Reputation: 45
I know that this is basic, but I cannot figure it out for whatever reason.
I'm trying to return some model data and the majority of the time I return it with pluck
, but pluck is returning an array. How do I return the value without the array?
<dd><%= Goal.where(id:post.attachid).pluck(:title) %></dd>
This is the code that I have and it is returning, for example, ["Computer"]
How do I just make it return Computer
Upvotes: 0
Views: 264
Reputation: 107057
In cases in which you expect the database to only return one record you might want to use find_by
instead of where
.
dd><%= Goal.find_by(id: post.attachid).title %></dd>
find_by
always returns only a single record while where
always returns an array-like ActiveRecord::Relation.
Upvotes: 2
Reputation: 2883
It's interesting to check what's the SQL generated by activerecord (you could verify that in your console):
Goal.where(id: post.attachid).pluck(:title)
Will produce something like:
SELECT "goals"."title" FROM "goals" WHERE "goals"."attachid" = $1 [["id", 1]]
I guess a cheaper alternative for what you want to achieve would be:
Goal.select(:title).find(post.attachid).title
That would produce:
SELECT "goals"."title" FROM "goals" WHERE "goals"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
That are many ways you could achieve the same thing, I would advise you to experiment, observe the SQL output and find the one that suit you best.
Upvotes: 1
Reputation: 3749
Depending on your needs, you can do
= Goal.where(id:post.attachid).pluck(:title).to_s
or
= Goal.where(id:post.attachid).pluck(:title).join(", ")
This would produce a result like
#> Computer, Laptop, Mouse...
Upvotes: 2