Hello, I’m having trouble using simple_form to create a nested model form. I’ve searched the wiki and the mailing list here, but have not come across anything to address the problem. I followed this guide on the wiki, and I want my associated model comment to post through product to the comment controller (using Rails 5). Currently the update action on the product controller is getting triggered, however, so I’m thinking that the form is interpreting the wrong model and URL/method.
In view/products/show.html.erb
I have:
div class="comments">
<h2>Add Comment</h2>
<%= render "comments/form" %>
</div>
view/comments/_form.html.erb
<%= render 'shared/error_messages', object: @product %>
<%= render 'shared/error_messages', object: @comment %>
<%= simple_form_for @product do |p| %>
<%= p.simple_fields_for :comment do |c| %>
<%= c.input :description %>
<%= c.button :submit, "Add Comment" %>
<% end %>
<% end %>
models/product.rb
class Product < ApplicationRecord
belongs_to :user
has_many :comments, inverse_of: :product
accepts_nested_attributes_for :comments
end
models/comment.rb
class Comment < ApplicationRecord
belongs_to :user
belongs_to :product, inverse_of: :comments
end
products_controller.rb
def show
@product = Product.find(params[:id])
@comment = Comment.new
@comments = @product.comments.order(created_at: :desc)
end
def update
@product = Product.find(params[:id])
if @product.update_attributes(product_params)
flash[:notice] = 'Your product has been successfully updated!'
redirect_to @product
else
render 'edit'
end
end
comments_controller.rb
def create
@product = Product.find(params[:product_id])
@comment = @product.comments.build(comment_params)
if @comment.save
flash[:notice] = "Your review was successfully posted!"
redirect_to @product
else
render "products/show"
end
end
Thank you in advance!
I was able to get around this with:view/comments/_form.html.erb
<%= simple_form_for [@product, @comment] do |f| %> <%= f.input :description %> <%= f.button :submit, "Add Comment" %> <% end %>
I thought that I had previously received an error with similar syntax but I guess it was do to an unrelated issue. I also found that I had a validation issue with a foreign key, which could have thrown me off from the original syntax. I’m surprised that this syntax is not in the wiki though? I know it is very close to the original Rails form_for syntax and that is documented in the API and guides, but I assumed it didn’t work with simple_form when I got an error. Thanks anyways.