First off, I would like to ask for your patience since this question is going to be really noobish. I've tried researching to no avail, as I can't put everything into place.
Anyway, I need to be able to render items in the database I will create as JSON. However, it is nested and I am unsure how would I go about creating the model for it:
{
"name": "name",
"description": "description",
"review": [
{
"rating": "rating",
"content": "content"
},
{
"rating": "rating",
"content": "content"
}
]
}
Creating the Database
Do I create two tables first (i.e. Item and Review), like so?
rails g model Item name:string description:string review:string
rails g model Review rating:string content:string
I've read that I need the accepts_nested_attributes_for method, but again, I am unsure how to use it.
class Item < ActiveRecord::Base
has_many :reviews
accepts_nested_attributes_for :reviews
end
class Review < ActiveRecord::Base
belongs_to :item
end
Populating the Database
If by some chance the above is correct, how do I actually populate the database using the console or seed.rb?
Rendering as JSON
This is what I have for non-nested entries:
def index
@items = Items.all
render :json => @items.as_json(:except => [:id, :created_at, :updated_at])
end
As you can tell, I am confused and lost. I would very much appreciate any input. Thank you.