Wilson
Wilson

Reputation: 181

Confused about how the render works in rails

I'm still fairly new to rails, but I've been trying to figure it out by building a bunch of simple projects like blogs, forums, clones over the weekend.

One of the blogs that I'm working on is a typical blog with users(devise), posts, and comments. I've been following a tutorial for this.

The thing that I've been really confuse on is setting up the comments and rendering it.

The tutorial teaches me to make a partial for comment in the comment view named _comment.html.erb and then another for form _form.html.erb . I fully understand that to call the form i just do render 'comments/form' but for the comment.html.erb i need to render @post.comments how come it's not 'comments/comment'? Why is it comments with the S?

I've tried reading up on render and plurization on rails, but most of them just talk about the model.

Upvotes: 0

Views: 60

Answers (1)

Rob Wise
Rob Wise

Reputation: 5120

There are two convention over configuration things going on here that may be causing you some confusion but are meant to save time.

Rails will automagically find the right partial if it follows naming conventions, meaning if your model is Comment that the view partial is located in app/views/comments/_comment.html.erb. That means you don't have to specify the location of the partial when calling render, but instead can just pass the model object directly and Rails figures out that you want it to render the partial and finds it on its own.

The reason it's comments plural here is that you are rendering all of the comments as a collection, not just a single comment. It's a convenience feature to allow the developer to simply tell Rails to render a collection and it will automagically know to use the corresponding partial. It's identical to typing:

@post.comments.each do |comment|
  render 'comments/comment`, object: comment
end

Note how the above code is calling render directly on a model object so we don't have to bother specifying the location of the partial (again, assuming you followed the convention when naming and locating things). If we named the partial something else, then we'd have to specify the location like your other examples.

Upvotes: 0

Related Questions