Rails 4: ActiveRecord => can't "select" has_one :through field from db -
Rails 4: ActiveRecord => can't "select" has_one :through field from db -
i trying retrieve 1 field "has_one :through" association. assuming have next model:
class createpersons < activerecord::migration def alter create_table :person |t| t.string :first_name t.string :last_name t.date :age end end def alter create_table :location |t| t.decimal :longitude t.decimal :latitude t.string :city t.string :state t.references :person end end def alter create_table :forecasts |t| t.timestamp :time t.text :summary t.decimal : precipitation t.references :location t.timestamps end end end
... , next model:
class location < activerecord::base belongs_to :person belongs_to :forecast end class forecast < activerecord::base belongs_to :locaiton has_one :person, :through => :location end class person < activerecord::base end
.. , want create query using activerecord pulls out persons first name based on forecast (i know stupid, excercise); this:
# realize bad query, i'm putting here create question stronger forecast.where("percipitation > ?", 1.5).select(:first_name)
or in sql terms
select first_name forecast fc inner bring together locaiton loc on loc.id = fc.location_id inner bring together person on person.id = loc.person_id precipitation > 1.5
so have tried this:
forecast.joins(:person).where("percipitation > ?", 1.5).select(:person) # forecast.joins(:person).where("percipitation > ?", 1.5).select(:person).to_sql # select 'person' forecast fc # inner bring together locaiton loc on loc.id = fc.location_id # inner bring together person on person.id = loc.person_id # fc.percipitation > 1.5
this returns me empty instances of forecast object
so tried this:
forecast.joins(:person).where("percipitation > ?", 1.5).select("person.first_name") # forecast.joins(:person).where("percipitation > ?", 1.5).select("person.first_name").to_sql # select 'person.first_name' forecast fc # inner bring together locaiton loc on loc.id = fc.location_id # inner bring together person on person.id = loc.person_id # fc.percipitation > 1.5
however, results in colleciton of empty forecast objects
however, doing results in want, but after db has been queried:
result = forecast.joins(:person).where("precipitation > ?", 1.5) result.each |forecast| puts forecast.person.first_name # => "john", "bob", "jim" end
why can't first_name out of db using select , pull first_name out of database? i'm missing something.
i don't know why solution works @ all.
do way:
forecast.where("precipitation > ?", 1.5).joins(:person).pluck("person.first_name")
it homecoming array of first names.
if need utilize select
(to scope):
forecast.where("precipitation > ?", 1.5).joins(:person).select("person.first_name")
ruby-on-rails select activerecord ruby-on-rails-4.1 has-one-through
Comments
Post a Comment