2

The article model has many comments, and the comment belongs to the article.

And the following is a part of the article partial.

  <%= link_to article.title, article %>
  <% if article.owned_by? current_user %>
      <span class='actions'>
        <%= link_to "Edit", edit_article_path(article) %>
        <%= link_to "Delete", article, confirm: "Are you sure?", method: :delete %>
      </span>
  <% end %>

And the following is a part of the comment partial.

<%= comment.name %> &lt;<%= comment.email %>&gt; commented:
<% if @article.owned_by? current_user %>
  <span class="actions">
    <%= link_to 'Delete', [@article, comment],
                :confirm => 'Are you sure?', :method => :delete %>
  </span>
<% end %>

Can you tell why the article is used in the article partial while the @article is used in the comment partial? Why not @article in the article partial?

I am sorry if my question is too easy to you, but it's really confusing to me.

Tobias
  • 4,523
  • 2
  • 20
  • 40
Sookie J
  • 823
  • 2
  • 8
  • 16
  • 3
    the `article` variable is a local variable (accessible only in the block it has been defined). The `@article` variable is shared between the view and the partials. The `@variables` are usually set in the controller, whereas the local variables are usually set for a part of code / view. But you can give a local variable as argument to the partial, something like `render 'my_partial', locals: article: local_article_variable` – MrYoshiji Nov 26 '15 at 14:58
  • 1
    Please add your view and your controller code. We have to know how your controller and the view behave because there are multiple ways to do the same thing. – Tobias Nov 26 '15 at 15:07

1 Answers1

3

Check your code, you probably have something like this somewhere:

<%= render partial: '_some_partial.html.erb', locals: { article: @article }

As pointed out in the comment by MrYoshiji, @article is an instance variable, set in the controller, while article is a local variable for that partial.

It is considered a good practice to use only local variables in the partials, as this allows you to reuse them much more easily, including between the views.


UPDATE

If by chance in your Comment model you have something like this:

class Comment < ActiveRecord::Base
  belongs_to :article
end

then in the comment partial you can avoid both instance variable and local variable by using: comment.article in their place.

bosskovic
  • 2,034
  • 1
  • 14
  • 29
  • 2
    Yeah or even `render @article` in newer versions of Rails. –  Nov 26 '15 at 15:03
  • 1
    local variables for a partial is the equivalent of a method's argument. You send it data which is scoped to the partial only. If the partial is tied to one instance and you couldn't do : `render partial: '_some_partial.html.erb', locals: { article: @blog.articles.first } for example... – charlysisto Nov 26 '15 at 15:19