2013-12-16 140 views
2

首先,我想請問你的耐心,因爲這個問題會變得非常不好。我試過研究無濟於事,因爲我不能把所有的東西都放到位。在Rails中嵌套的JSON

無論如何,我需要能夠呈現數據庫中的項目,我將創建爲JSON。但是,嵌套,而且我不確定我將如何去創造它的型號:

{ 
"name": "name", 
"description": "description", 
"review": [ 
    { 
     "rating": "rating", 
     "content": "content" 
    }, 
    { 
     "rating": "rating", 
     "content": "content" 
    } 
] 
} 

創建數據庫

難道我首先創建兩個表(即項目和評論),像這樣?

rails g model Item name:string description:string review:string 
rails g model Review rating:string content:string 

我讀過,我需要的accepts_nested_attributes_for方法,但同樣,我不能確定如何使用它。

class Item < ActiveRecord::Base 
    has_many :reviews 

    accepts_nested_attributes_for :reviews 
end 

class Review < ActiveRecord::Base 
    belongs_to :item 
end 

填充數據庫

如果由於某些原因上面是正確的,實際上,我怎麼填充使用控制檯或seed.rb數據庫?

呈現爲JSON

這是我對非嵌套項:

def index 
    @items = Items.all 
    render :json => @items.as_json(:except => [:id, :created_at, :updated_at]) 
end 

正如你所知道的,我很迷茫,失去了。我非常感謝任何意見。謝謝。

回答

4

它看起來像你幾乎在那裏,並且一定在正確的軌道上。

當您創建的模型,您將不再需要爲review:string項目,但你需要一個item_id以供審閱(持有相關Item.id),像這樣的:

rails g create Item name:string description:string 
rails g create Review rating:string content:string item_id:integer 

的方式軌協會的工作是它將存儲item.id的關聯Item記錄在review.item_id。它會自動執行此操作,所以您只需使用它們即可。從項目

new_review = Review.create(rating: 'great', content: 'Wonderfully done') 
new_item = Item.create(name: 'My Item', description: 'My Item description') 
new_item.reviews << new_review 

要訪問相關的審查(S):

要創建審查和項目之間的關聯

new_item.reviews.each do |review| 
    review.rating 
    review.content 
end 

因爲它是一個has_many關係的Item一個實例將有一個reviews方法,該方法返回Review對象的數組,該對象的item_id與當前Item.id相匹配。

同樣,Review的一個實例將有一個item方法(注意這裏單數使用),它只返回單個關聯的Item記錄對象。

有意義嗎?

此外,當您使用JSON中的關聯輸出記錄時(正如您在示例中所做的那樣),它應該創建接近您的示例顯示的輸出。

渲染你的JSON如下:

@items = Item.all 
render :json => @items.to_json(:include => [:reviews], :except => [:id, :created_at, :updated_at]) 
+0

謝謝您的答覆。不幸的是,我被困在儲存新作評論中。它告訴我它找不到方法 - 'undefined method'reviews''。 – styx

+0

你是否已經遷移了你的數據庫?:'rake db:migrate' – benjaminjosephw

+0

確保你已經創建了類似於你的例子中的關聯,並用'rake db:migrate'應用了數據庫遷移。 – Donovan