Reputation: 3794
I'm a rails newbie !
I would like to know why in that different case, one work, one doesn't.
### in my controller ###
def watch_randurl
# @dat = Video.where(url_rand: params[:url_rand])
@dat = Video.find(1)
end
With find(1)
, I have my database and in my view this work!
### in my view ###
<%= @dat.url_rand %> <br>
but with the where
I have a
undefined method 'url_rand' for <Video::ActiveRecord_Relation:0x007fcbfeece1c8>
Ps: sorry for my english :/ Of course, I need this work with a where.
SOLVE with : Video.where(url_rand: params[:url_rand]).first
Thank you !
Upvotes: 1
Views: 39
Reputation: 181
If what you are looking for is a way to get a record based on a condition you could use find_by.
find_by(*args) source
Finds the first record matching the specified conditions.
In your case you could use:
@video = Video.find_by(url_rand: params[:url_rand])
@video would be the first video matching the condition.
Upvotes: 0
Reputation: 6426
@dat = Video.find(1)
returns a single Vedio object that's why you can use @dat.url_rand
.
But when you use where like @dat = Video.where(url_rand: params[:url_rand])
you will get an array of objects in @dat
. So @dat will be an array of objects here.
In this case, you'll have to follow Pavan's advise and do something like this:
@dat.first.url_rand
or @dat[0].url_rand
Upvotes: 0
Reputation: 33542
But with the where i have a undefined method 'url_rand' for Video::ActiveRecord_Relation:0x007fcbfeece1c8
where
returns an ActiveRecord_Relation
, so in that case, you need to modify @dat = Video.where(url_rand: params[:url_rand])
, to @dat = Video.where(url_rand: params[:url_rand]).first
or
You can iterate over @dat
like below, without changing the value of @dat
<% @dat.each do |dat| %>
<%= dat.url_rand %> <br>
<% end %>
Upvotes: 1