我想在3个模型之间创建一个多态关联 - 用户,帖子和评论。但是当我关联用户和帖子并添加表格' user_id'在视图&post; / index'浏览器显示错误
undefined method `name' for nil:NilClass
这是我的观点posts / index.html.haml
- @posts.each do |post|
= post.title
= post.body
= post.user.name
这是我的帖子/ 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"
这是我的控制器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
这是我的迁移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
这是我的模特帖子
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 >
如何解决?
抱歉我的英文不好
答案 0 :(得分:2)
每个人都填写了user_id
吗?我猜这不是错误。简单的解决方法是在查找其名称之前测试是否存在用户。简单地说:
= post.user.name if post.user.present?
或,简短而甜蜜:
= post.user.try(:name)