loading...

Day 46 : #100DaysofCode - Still reviewing form_for

sincerelybrittany profile image Brittany ・2 min read

I am still going over forms in Ruby on Rails. Something that I learned today is how to create a form to add comments to a profile page. I think something that resonated with me today is that you can build from a form_for tag. For example, if you wanted to create a new profile with comments you could add @profile.comments.build to the form_for tag. That will essentially return a new object with the profile.comments attributes and link it to the object without saving it. For example, after setting up your associations so that a profile and user can have many comments you would add the following to the profile show page:

<%= form_for @profile.comments.build do |f| %>
  <%= f.hidden_field :profile_id %>
  <p>
    <%= f.collection_select :user_id, User.all, :id, :username %>
  </p>  
  <p>
    <%= f.label :content, "New Comment" %><br>
    <%= f.text_area :content %>
  </p>
  <br/>
  <%= f.submit %>
<% end %>

If you noticed, <%= f.hidden_field :profile_id %> is added to the form_for tag as well. That piece of code is gold, it allows us to send the profile_id over to a controller as a hidden param so that it can be referenced in your create method.

The @profile.comments.build allows rails to know that we want to reroute to the comments controller and from there you can save the params and create a new comment and reroute to that profile page. Like this:

The controller:

  def create
    @comment = Comment.create(comment_params)
    redirect_to @comment.profile
  end

  private

  def comment_params
    params.require(:comment).permit(:content, :profile_id, :user_id, user_attributes:[:username])
  end

I can definitely see why people love rails. It is simple once you learn all the syntax. I look forward to create projects using Ruby on Rails.

As always, thanks for reading!

Sincerely,
Brittany

Posted on by:

sincerelybrittany profile

Brittany

@sincerelybrittany

Developer | Software Engineer 👩🏾‍💻 | Determined | Music & Dance | Completed #100DaysofCode | #WomenWhoCode

Discussion

markdown guide