Sunday, 2 June 2013

Attributes considered as method in rails

Attributes considered as method in rails

With rails I have an articles tables with a column named category_id. In my index page I use debug method for print the content of my article and I have this result :
article.category
The full code
<% if @articles.blank? %>
    <h3>Aucun articles à afficher</h3>
<% else %>
<% @articles.each do |article| %>
<%= debug article.category %>
<div class="article">
    <img src="assets/img/bootstrap-mdo-sfmoma-08.jpg" class="img-polaroid pull-left" >
    <ul class="breadcrumb">
        <li><a href="/tutoriels">Articles</a></li>
        <li><span class="divider">/</span></li>
        <li><a href="article.html"></a></li>
        </li>
    </ul>
    <h1 class="title"><%= link_to article.title, article %></h1>
    <p class="author">
        <%= link_to article.user.username, "/users/#{article.user.id}" %> le
        <%= I18n.l article.updated_at, :format => :article %>
        <a href="#">16 Comments</a>
     </p>
    <div class="clearfix"></div>
    <hr>
</div>
<% end %>
<% end %>
The result :
--- !ruby/object:Category
attributes:
    id: 1
    title: Développement web
    section: 1
    slug: developpement-web
But if I try to print the title of my category like this
<%= article.category.title %>
I have this error :
undefined method `title' for nil:NilClass
In rails console its work perfectly
irb(main):008:0> article = Article.find_by_id 1

  Article Load (1.0ms)  SELECT `articles`.* FROM `articles` WHERE `articles`.`id` = 1 LIMIT 1

=> #<Article id: 1, title: "Ruby Mass Assignment, Rails, and You", slug: "ruby-mass-assignment-rails-and-you", body: "Content of article", category_id: "1", user_id: "1", validate: "2", created_at: "2013-06-02 06:05:13", updated_at: "2013-06-02 06:05:13">

irb(main):009:0> article.category.title

  Category Load (0.0ms)  SELECT `categories`.* FROM `categories` WHERE `categories`.`id` = 1 LIMIT 1

=> "Développement web"
Thanks in advance and sorry for my english.

No comments:

Post a Comment