I have a nested attribute and I can display values, but it is not saving into database why?
I have a model review
and I want to nest attribute comments
review migration file
class CreateReviews < ActiveRecord::Migration
def change
create_table :reviews do |t|
t.belongs_to :reviewable, polymorphic: true
t.timestamps
end
add_index :reviews, [:reviewable_id, :reviewable_type]
end
end
review model
class Review < ActiveRecord::Base
attr_accessible :rating, :user_id, :comments_attributes, :service
has_many :comments, as: :commentable
belongs_to :user
belongs_to :reviewable, polymorphic: true
accepts_nested_attributes_for :comments
end
comments migration file
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :content
t.belongs_to :commentable, polymorphic: true
t.integer :user_id
t.timestamps
end
add_index :comments, [:commentable_id, :commentable_type]
end
end
comment model
class Comment < ActiveRecord::Base
attr_accessible :content, :user_id
belongs_to :commentable, polymorphic: true
belongs_to :user
belongs_to :review
end
This is the form
<%= form_for [@reviewable, @review], :html => {:multipart => true} do |f| %>
<%= f.fields_for :comments, @review.comments.build do |field| %>
<%= field.label "Comment" %></div>
<%= field.text_field :content %>
<% end %>
<%= f.submit %>
<% end %>
It displays the fields, but how come when I save, it doesn't save?
I tried to display like this:
<%= @review.comments %>
Here's my review controller
def new
@review = @reviewable.reviews.new
@review.comments.build
end
Thanks for your help!
EDIT:
Review controller: create method
def create
@review = @reviewable.reviews.new(params[:review])
@review.user = current_user
if @review.save
redirect_to @reviewable, notice: "review created."
else
render :new
end
end