Melvin Ch'ng Melvin Ch'ng - 4 months ago 10
Ruby Question

Unable to access values from the table attribute

I am trying get the values from

front, rear, side
attributes from
tints
entity.

manufacturers
{id, name}


models
{id, manufacturer_id, name}


tints
{id, manufacturer_id, model_id, front, side, rear}


This is my
tints_controller.rb


def generate
@manufacturers = Manufacturer.find(params[:tint][:manufacturer_id])
@models = Model.find(params[:tint][:model_id])
@price_front = Price.find(params[:price][:price_front])
@price_rear = Price.find(params[:price][:price_rear])
@measurements = Tint.where('manufacturer_id' => @manufacturers).where('model_id' => @models)
end


I received an error when I was trying to do
<%= @measurements.rear %>
in my
generate.html.erb


undefined method `rear' for #<Tint::ActiveRecord_Relation:0x0000000c628610>


Here are the debug screen

Request

Parameters:

{"utf8"=>"✓",
"authenticity_token"=>"jfV6SUkNdKWO1f1fyzqS4eLbvszjDPNm2E81M90lnvPArYScSjcjQlxsJdcuqQMJ+mSecCsyVQlhz2cpAH1DUw==",
"tint"=>{"manufacturer_id"=>"6", "model_id"=>"3"},
"price"=>{"price_front"=>"1", "price_rear"=>"2"},
"commit"=>"Submit"}


However, when I do
<%= @measurements.inspect %>
, it showed the line below, indicating the
@measurements
in the
tints_controller
is defined correctly. It shows it is able to get the entire row from the table by searching for the correct
model_id
and
manufacturer_id
. But I am unable to get the
front, side, rear
values as in
int
directly by doing
<%= @measurements.front =>


#<ActiveRecord::Relation [#<Tint id: 1, manufacturer_id: 6, model_id: 3, front: 40, side: 50, rear: 60, created_at: "2016-07-22 04:14:49", updated_at: "2016-07-22 04:14:49">]>


What I have done:
I tried to do
<%= @measurements[:front] =>
and
<%= @measurements[:id][:front] =>
, and I still get errors.

Answer

When you select from ActiveRecord using where, it returns an ActiveRecord_Relation object, which is always an array of the associated objects, because multiple objects can be returned from a where query.

You need to either specify which Tint to be selected in the view:

@measurements.first.rear

or you need to modify your controller to only select the first object which is returned:

@measurements = Tint.where('manufacturer_id' => @manufacturers).where('model_id' => @models).first