Reputation: 347
I want to create a polymorphic association between 3 models - User, Post and Comment.But in step when I associate User and Post and added form 'user_id' in view 'posts/index' browser show me an error
undefined method `name' for nil:NilClass
this is my view posts/index.html.haml
- @posts.each do |post|
= post.title
= post.body
= post.user.name
this is my view posts/new.html.haml
= form_for @post do |f|
= f.text_field :title, placeholder: "title"
= f.text_field :body, placeholder: "text"
= f.text_field :user_id, placeholder: "user"
= f.submit "Send"
this is my controller posts_controller
class PostsController < ApplicationController
def index
@posts = Post.all
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to posts_path
end
end
private
def post_params
params.require(:post).permit(:title, :body, :user_id)
end
end
this is my migration create_posts.rb
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :title
t.text :body
t.references :user, index: true
t.timestamps
end
end
end
and this is my model Post
class Post < ActiveRecord::Base
belongs_to :user
end
UPD
2.1.5 :001 > Post.all Post Load (0.6ms) SELECT "posts".* FROM "posts" => #<ActiveRecord::Relation [#<Post id: 1, title: "title", body: "body", user_id: nil, created_at: "2014-12-04 13:27:35", updated_at: "2014-12-04 13:27:35">, #<Post id: 2, title: "title", body: "body", user_id: nil, created_at: "2014-12-04 13:47:36", updated_at: "2014-12-04 13:47:36">, #<Post id: 3, title: "title", body: "body", user_id: 1, created_at: "2014-12-04 13:50:50", updated_at: "2014-12-04 13:50:50">, #<Post id: 4, title: "title", body: "body", user_id: 2, created_at: "2014-12-04 13:57:15", updated_at: "2014-12-04 13:57:15">]>
2.1.5 :002 >
how fix?
sorry for my bad English
Upvotes: 0
Views: 54
Reputation: 50057
Does every have post a user_id
filled in? I am guessing that is the error not. The simple workaround is to test if there is a user present, before looking for its name. So simply:
= post.user.name if post.user.present?
or, short and sweet:
= post.user.try(:name)
Upvotes: 2