Still can't get this working after trying several things noted in the initial comments - I've revised below to reflect those efforts / clarify a few things.
Problem summary: I cannot create a new Post (an answer) where the parent_id of that Post equals the id of the Post for the associated question. The user starts on the posts#show page for the question Post, and clicks "Answer". I'd have thought the code below would pass the id of the question Post to the answer Posts' parent_id. But it does not. It returns parent_id = nil
I have a Posts model. A Post has a post_type_id of 1 (question) or 2 (answer).
All Posts where post_type_id = 2 have a parent_id that points to the id of the question being answered.
On posts#show I have:
<% case post_type %>
<% when 1 %>
<%= link_to 'Answer', new_post_path(:parent_id => @post.id) %>
<% else %>
<% end %>
When I click on that it takes me to the new_post page and the url is: //localhost:3000/posts/new?parent_id=6
(The question in this example has id = 6, so I think that looks correct.)
In my Posts Controller I have:
def new
@post = Post.new
end
def show
end
def create
@post = Post.new(post_params)
@post.user_id = current_user.id
@post.parent_id = params[:parent_id]
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: @post }
else
format.html { render :new }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
def post_params
params.require(:post).permit(:user_id, :post_type_id, :title, :content, :accepted_answer_id, :parent_id, :score, :answer_count, :favorite_count)
end
My routes are:
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
In new.html.erb I have:
<h3>New Post</h3>
<%= render 'form' %>
<%= link_to 'Back', posts_path %>
And _form.html.erb is:
<%= simple_form_for(@post) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%- f.association :user %>
<%= f.input :post_type_id, collection: post_types, label: 'What do you want to do?' %>
<%= f.input :title %>
<%= f.input :content %>
<%- f.input :accepted_answer_id %>
<%- f.input :parent_id %>
<%- f.input :score %>
<%- f.input :answer_count %>
<%- f.input :favorite_count %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
I'd really appreciate any suggestions on how I can get this working.
Thanks!