Rails belongs_to issue in the views

Posted by Jacobo Tibaquira on Stack Overflow See other posts from Stack Overflow or by Jacobo Tibaquira
Published on 2010-06-11T21:01:28Z Indexed on 2010/06/11 21:22 UTC
Read the original article Hit count: 218

Filed under:
|
|
|

Hi,

Im having problems with an association in rails:

Currently I have Post and User models, and the relationship is set this way:

class User < ActiveRecord::Base
  attr_accessible :username, :name, :lastname
  has_many :posts
end

class Post < ActiveRecord::Base
  attr_accessible :title, :body
  belongs_to :user
end

However, in my app/views/posts/index.html.haml when Im trying to access the username for the post I get this error:

undefined method `name' for nil:NilClass

This is my view:

- title "Posts"

%table
  %tr
    %th Title
    %th Body
    %th Author
  - for post in @posts
    %tr
    %td= h post.title
    %td= h post.body
    %td= h post.user.name
    %td= link_to 'Show', post
    %td= link_to 'Edit', edit_post_path(post)
    %td= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete

%p= link_to "New Post", new_post_path

Any thoughts of what Im doing wrong will be appretiated

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby