DEV Community 👩‍💻👨‍💻


Posted on

Day 46 : #100DaysofCode - Still reviewing form_for

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 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 do |f| %>
  <%= f.hidden_field :profile_id %>
    <%= f.collection_select :user_id, User.all, :id, :username %>
    <%= f.label :content, "New Comment" %><br>
    <%= f.text_area :content %>
  <%= f.submit %>
<% end %>

Enter fullscreen mode Exit fullscreen mode

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 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


  def comment_params
    params.require(:comment).permit(:content, :profile_id, :user_id, user_attributes:[:username])
Enter fullscreen mode Exit fullscreen mode

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!


Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.