嵌套的关联属性我有三个型号如下:Rails的:包括针对
#Product Model
class Product < ActiveRecord::Base
belongs_to :user
has_one :address
validates :title, :description, :user_id, presence: true
validates :product_type, numericality:{:greater_than => 0, :less_than_or_equal_to => 2}, presence: true
accepts_nested_attributes_for :address
end
#Address Model
class Address < ActiveRecord::Base
belongs_to :city
belongs_to :product
def related_city
city = address.city
end
end
#City Model
class City < ActiveRecord::Base
has_many :addresses
end
我取一个产品,但我需要包括关联的属性以及在除了几个属性我JSON响应。 以下是我迄今所做的:
def show
product = Product.find(params[:id])
render json: product.to_json(:include => { :address => {
:include => { :city => {
:only => :name } },
},:user =>{:only=>{:first_name}}}), status: 200
end
这是给我一个语法错误。如果我删除用户,它工作正常,但我也需要用户名称作为回应。此外,我将如何使用ruby的新哈希语法编写上述代码?
使用新的语法通常会导致更少的内容出错。 ':include => {...}'变成'include:{...}'这样更容易阅读。使用旧风格的唯一原因是如果你仍然有理由使用可怕的1.8版本。 – tadman