Rails 4 - NoMethodError未定义方法

时间:2013-10-17 02:34:10

标签: ruby-on-rails-4 nomethoderror

当我调用<%= @ post.admin_user.name%>时,我收到NoMethodError,不知道如何修复它。

提取的来源(第4行):

<h1><%= @post.title %></h1>
<p><%= @post.body %></p>
<small>Post created at <%= @post.created_at.strftime('%b %d. %Y') %></small><br/><br/>
<%= @post.admin_user.name %>
<p>Category: <%= link_to @post.category.name, category_path(@post.category.id) %></p>
<%= link_to 'Edit Post', edit_post_path %> | <%= link_to 'Go Back', posts_path %> |     <%= link_to 'Delete Post', @post, :confirm => "Don't do it man!", :method => :delete %>
</div>

显示c:/Sites/blog/app/views/posts/show.html.erb,其中第5行被提出:

nil的未定义方法`name':NilClass


这是我的posts_controller.rb

  class PostsController < ApplicationController
     def index
 @post = Post.all


  end

  def new
 @post = Post.new
 @category = Category.all
  end


  def create
  @post = Post.new(post_params)
   if @post.save
   redirect_to posts_path, :notice => 'Your post has been posted!'
   else
   render 'new'
   end
  end


  def post_params
      params.require(:post).permit(:title, :body, :category_id, :admin_user_id, :admin_user, :name)
  end


  def edit
  @post = Post.find(params[:id])
  end

  def update
  @post = Post.find(params[:id])
  if @post.update_attributes(post_params)
     redirect_to post_path, :notice => 'Your post has been updated.'
     else
     render 'new'
    end  
  end

  def show
  @post = Post.find(params[:id])
  @user = AdminUser.all
  end

  def destroy
  @post = Post.find(params[:id])
      @post.destroy
      redirect_to posts_path, :notice => 'Your post has been deleted.'
   end




   end

这是我的post.rb

class Post < ActiveRecord::Base

  belongs_to :category

 belongs_to :admin_user


end

我的admin_user.rd

class AdminUser < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, 
         :recoverable, :rememberable, :trackable, :validatable

   has_many :posts


end

0 个答案:

没有答案