连接表中的数据不是类型转换

时间:2011-03-07 09:50:18

标签: ruby-on-rails

我正在使用连接查询来获取另一个表的属性以及查询。

city = City.first(:select => "cities.*, states.name as state_name, states.time as state_time"
                  :joins => "LEFT JOIN states on cities.state_id = states.id",
                  :conditions => ["states.name = ?", params[:state]])

这里的问题是,当我从city.state_time这样的联接表中获取值时,我将获得类似2010-11-12 05:00:00的字符串而不是时间对象(Rails没有对这些进行类型转换)字段)。这是有道理的,因为我正在调用City模型,并且用于类型转换时间列的方法将在State模型中。我将不得不明确地解析这样的时间,并且还必须与时区问题作斗争。 (因为Rails在给出Time对象时会进行一些自定义,我将不得不为这些列执行这些操作)。有没有办法在进行连接时将列链接到State。我想到的一种方法是这样的。

state = State.new(:name => city.state_name, :time => city.state_time)

并使用state.namestate.time。还有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

这可能是你想要的:

class City < ActiveRecord::Base
  belongs_to :state
end

class State < ActiveRecord::Base
  has_many :cities
end

a = City.joins(:state).includes(:state).where(['states.name = ?', params[:state]]).first
a.state.time

这可以使用内连接并具有一些条件:

  • 城市必须只属于一个州。如果城市不属于任何州,则由于内部联接
  • ,查询将不会返回该状态

Rails 2语法

a = City.find(:all, :conditions => ['states.name = ?', params[:state]], :joins => :state, :include => :state)
相关问题