Reputation: 139
There are posts and comments form for each. I'm trying to add a comment to every post through the form. It's all happening on the same page.
View file code:
<% @posts.each do |post| %>
<%=post.title%>
<%=post.text%>
<%post.comments.each do |com|%>
<h3> <%=com.content%> </h3>
<%end%>
<%= form_for post.comments.build do |f| %>
<p>comments:</p>
<%= f.text_area :content, size: "12x12" %>
<%=f.submit%>
<% end %>
<% end %>
Comments controller code:
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.build(comment_params)
@comment.save
redirect_to root_path
end
It seems that program can not access to :post_id. I have all associations in my models and :post_id in my db schema.
Upvotes: 0
Views: 42
Reputation: 1915
You need to add <%= f.hidden_field :post_id %>
in your form and permit :post_id
in comment_params.
Also, you may want to reduce create method code to one line.
def create
Comment.create(comment_params)
redirect_to root_path
end
Upvotes: 1
Reputation: 139
I found a problem. The mistake is in searching by params[:post_id], while i need to by [:comment][:post_id] after adding the hidden_field
Upvotes: 0
Reputation: 630
You need to permit :post_id
for your strong parameters in the comments controller:
def comment_params
params.require(:comment).permit(:content, :post_id)
end
Upvotes: 0