Bla*_*ite 0 ruby activerecord join inner-join ruby-on-rails-3
我试图根据其父表中的键检索子对象.例如,我有一个Customer类,其中包含Stores表的"store_id"键.如果客户有"store_id"键,我想带回那个Store对象而不是父Customer对象.
编辑:这是一个sql语句显示我想要做什么.
所以SQL语句看起来像这样.
"SELECT storeS.*FROM FROM INNER JOIN store ON customers.store_id = storeS.id WHERE customers.id ='9'"
我知道sql可能是错误的,但这是一种非常简洁的方式来显示它.
我假设您正在使用具有开箱即用配置的rails(使用ActiveRecord).
按照惯例,"customers"表中的"store_id"键应与"stores"表中的"id"字段匹配.您还应该具有以下类模型设置:
class Store < ActiveRecord::Base
has_many :customers # this is not required for what you want to do here, but recommended
end
class Customer < ActiveRecord::Base
belongs_to :store
end
Run Code Online (Sandbox Code Playgroud)
假设这是真的,如果你有商店密钥,你可以这样做:
# assuming we have store key == 9
Store.find(key)
Run Code Online (Sandbox Code Playgroud)
或者,如果您已经有客户,您可以这样做:
# assuming we have customer.store_id == 9
customer.store
Run Code Online (Sandbox Code Playgroud)
或者,如果您只有客户密钥:
# assuming we have a customer key == 9
customer = Customer.find(9)
store = customer.store
Run Code Online (Sandbox Code Playgroud)