0

those are my routes:

  resources :forums, :shallow=>true do
    resources :topics, :shallow=>true do
      resources :posts
    end
  end

within topics/show.html.erb I added a form to leave a post (Post is like a comment for a Topic)

<%= form_for [@topic, @post] do |f| %>
    <div class="field">
    <%= f.label "content" %><br />
    <%= f.text_area :content %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

the problem is that the field :topic_id within the model Post stays empty. shouldn't it get the topic's id automatically?

thanks

1
  • Automatically? No. Show the code that saves your form data to it's new model instances. Commented Dec 10, 2012 at 12:36

1 Answer 1

1

The topic_id is not inside params[:post] in create action of your PostsController. So you need to assign topic_id to post in action manually, like this:

...
@post = Post.new(params[:post])
@post.topic_id = params[:topic_id]
if @post.save
  flash.notice "Post created successfully"
else
  flash.error "Error saving post"
end
...
Sign up to request clarification or add additional context in comments.

1 Comment

post = Topic.find(params[:topic_id]).posts.build(params[:post]) might be more resilient. Putting the Topic.find in a before filter for that controller would also be a good idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.