Home Rails Has_manybelongs_to中的conditions的写法
Post
Cancel

Rails Has_manybelongs_to中的conditions的写法

参考: https://stackoverflow.com/questions/20307874/what-is-the-equivalent-of-the-has-many-conditions-option-in-rails-4

在 Rails2/3 中, has_many 可以包含 conditions 

在 Rails 4+ 中,需要写成 ->, 例如:

class Payment < ActiveRecord::Base
  belongs_to :dish_order,-> { where(entity_class: "DishOrder") },  foreign_key: 'entity_id', class_name: 'dish_order'
end

注意:  -> {... } 这个参数的位置,必须要放到 第二个参数的位置。 (也就是 belongs_to :xx, -> {..},  foreign_key:.... )

-> {} 是一个 scope block,  可以包含:  where, includes, readonly , select 。 具体参考:  http://guides.rubyonrails.org/association_basics.html

This post is licensed under CC BY 4.0 by the author.