2016-04-03 69 views
0

嵌套的關聯屬性我有三個型號如下: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的新哈希語法編寫上述代碼?

+0

使用新的語法通常會導致更少的內容出錯。 ':include => {...}'變成'include:{...}'這樣更容易閱讀。使用舊風格的唯一原因是如果你仍然有理由使用可怕的1.8版本。 – tadman

回答

0

您可以使用此寶石解決這個問題:Active Model Serializers。它將允許您爲每個模型創建序列化器,並根據需要使用它們來呈現格式化的JSON。看一看,讓我知道。

0

問題是你的show方法的第五行有逗號包圍着花括號。這裏是哈希SANS逗號,在新的語法:

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 
+0

我試過上面的代碼,但是我得到這個錯誤:「/home/paras/rails/lost_and_found/app/controllers/api/v1/products_controller.rb:31:語法錯誤,意外的'}',期待=>用戶:{only:{:first_name}}}),status:200 ^「 – Paras

+0

哦,你可能需要從第6行移動到5的括號。我編輯了我的散列。 – trosborn

+0

沒有運氣。仍然收到以下錯誤:/home/paras/rails/lost_and_found/app/controllers/api/v1/products_controller.rb:31:語法錯誤,意外的'}',期待=>用戶:{only:{:first_name}} ),狀態:200^ #31 user:{only:{:first_name}}),status:200 – Paras