1

I am working on a basic blog system, where in my #post/show I have a form which submits to both Visitor and Comment models. Post/show has this form at the bottom of the page:

<%= form_for :visitor, url: comment_visitors_path do |f| %>
  <p>
    <%= f.label :fullname %><br>
    <%= f.text_field :fullname %>
  </p>

  <%= f.fields_for :comments do |c| %>
    <p>
        <%= c.label :message %><br>
        <%= c.text_area :message %>
    </p>
    ...
  <% end %>
<% end %>

For some long reason, I want to be able to pre-populate both visitor fields and comments fields. In the #post/show controller I can pre-populate the visitor's fullname like so:

def show
 @post = Post.find(params[:id])

 @visitor = Visitor.new(fullname: 'John', comments: [Comment.new(message: 'not working')])
 ...
end

But can't figure out how to pre-populate the values of fields_for, namely (comments: ...) does anyone have any ideas?

The above code does not fill in the textarea with the provided default value, would be nice if it did.

1 Answer 1

1

Substitute

<%= form_for :visitor, url: comment_visitors_path do |f| %>

with <%= form_for @visitor, url: comment_visitors_path do |f| %>

This did the trick for me.

Also, did you make sure to use

accepts_nested_attributes_for :comments

in your Visitor model? If you don't, fields_for will not prepopulate the comments (or work correctly).

Sign up to request clarification or add additional context in comments.

2 Comments

Oh yes, I do have accepts_nested_attributes_for :comments in Visitor model
I have edited the answer, I realized that using the :visitor symbol wasn't working locally.

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.