Reputation: 5637
Current Code
@current_site_name = 'SITENAME'
@current_site = Site.where(:name => @current_site_name)
@current_site_id = @current_site.id
Basically, the name
column in our Site
model is unique. We are selecting a row using the site name as a parameter.
I am returned: <ActiveRecord::Relation:0x59426bc1>
I understand that I cannot simply ask for @current_site.id
but is there any way to put the ID of the single activerecord into the variable @current_site_id
Again, there will always be one active record.
Upvotes: 1
Views: 2988
Reputation: 4293
Just to throw another solution out there, you can make use of Rails' dynamic finders that are created for your models.
@current_site = Site.find_by_name(@current_site_name)
This returns a single record (and thus doesn't require the use of first
) and might be seen as cleaner code in some people's opinion.
Upvotes: 0
Reputation: 6082
Hmm... This is quite strange.
Site.where(:name => @current_site_name).methods.include? :id #=> false
but
Site.where(:name => @current_site_name).instance_methods.include? :id #=> true
However,
Site.where(:name => @current_site_name).instance_eval "id" #=> NameError
and
Site.where(:name => @current_site_name).methods.include? "self.id" #=> NoMethodError
That said, a workaround assuming in your case, only one record should be returned is
Site.where(:name => @current_site_name).instance_eval('find_first').id
The find_first
method is protected
so we have to jump scope in its execution to avoid another NoMethodError
Upvotes: 0
Reputation: 2020
As you've seen, where
will return an ActiveRecord::Relation
(a set of rows), even if there's only one row that matches your criteria. You can make @current_site
be assigned to the row you want by changing the line to this:
@current_site = Site.where(:name => @current_site_name).first
Upvotes: 3