Question

I am trying link to the 'edit' action of a nested Comment from the 'index' action of its parent Articles controller. If no comment exists, then the link will go to the 'new' action.

resources :articles do
  resources :comments
end

The problem seems to be how to define @comment in the Articles controller in order to get the proper comment id with the associated article id.

The Articles controller contains:

def index
  @articles = Article.all
end

I can accomplish what I want by defining @comment in the View 'index.html.erb' (see below):

<% @articles.each do |article| do %>
  <% @comment = current_user.comments.where(article_id: article.id) %>
  <% if @comment.empty? %>
    <%= link_to "New Comment", new_article_comment_path(article) %>
  <% else %>
    <% @comment.each do |comment| %>
      <%= link_to "Edit Comment", edit_article_comment_path(article, comment) %>
    <% end %>
  <% end %>
<% end %>

But I would prefer to have @comment defined in the Articles controller. I am not sure how to implement '@comment = current_user.comments.where(article_id: article.id)' in the Articles controller without the id as it's the 'index' action.

Must be something simple I'm missing.

Was it helpful?

Solution

I don't know how it would work inside a controller. But I think it's better to move the method inside a helper anyway and call it from there. methods defined inside a helper are automatically available for your views

you can do this:

def comment(article)
    @comment = current_user.comments.where(article_id: article.id)
end

Then your view will look like this:

<% @articles.each do |article| do %>
   <% comment(article) %>
   ....more code....

Like you said, if you move this in the controller, where(article_id: article.id) will trip you as you don't know which article the id is bound to.

EDIT:

if you really want to access the method inside the controller, you can do as this post suggests:

class ArticlesController < ActionController::Base
  def comment(article)
      @comment = current_user.comments.where(article_id: article.id)
  end
   helper_method :comment(article)
end

but why go through the trouble when you can easily do this inside a helper.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top