首先,我想請問你的耐心,因爲這個問題會變得非常不好。我試過研究無濟於事,因爲我不能把所有的東西都放到位。在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
正如你所知道的,我很迷茫,失去了。我非常感謝任何意見。謝謝。
謝謝您的答覆。不幸的是,我被困在儲存新作評論中。它告訴我它找不到方法 - 'undefined method'reviews''。 – styx
你是否已經遷移了你的數據庫?:'rake db:migrate' – benjaminjosephw
確保你已經創建了類似於你的例子中的關聯,並用'rake db:migrate'應用了數據庫遷移。 – Donovan