【问题标题】:i am trying to show my posts title on show page but it shows this error again and again . i am beginner in rails我试图在显示页面上显示我的帖子标题,但它一次又一次地显示此错误。我是 Rails 的初学者
【发布时间】:2019-06-06 15:40:29
【问题描述】:

**我为帖子制作了控制器和模型,但无法显示我的帖子 显示页面上的标题,但我反复收到相同的错误**

my posts_controller code :


class PostsController < ApplicationController
    def index

    end

    def new 


    end
    def create
    #render plain: params[:post][:body].inspect
    @post = Post.new(post_params)
    if @post.save
        redirect_to posts_path
    else
        render "new"
    end
    end
   def show
    @post= Post.find(:id=>params[:id])
    # @article = "prateek"
   end
   private
   def post_params
    params.require(:post).permit(:title,:body)

   end
end

我的 show.html.erb 文件:

<h1><%= @post.title %></h1>

我的 post.rb 文件:

class Post < ApplicationRecord
end


**I expect the result but I didn't get anything right
 error = NoMethodError in Posts#show
    undefined method `title' for nil:NilClass**

【问题讨论】:

  • 你能发布控制台中存在的堆栈错误吗?
  • 你能把你的代码贴在github上吗
  • 我在发帖/10 或发帖/id 时得到了我的头衔,但是当我提交按钮时,我收到了路由错误,例如没有路由 [posts/new]

标签: ruby-on-rails ruby rubygems ruby-on-rails-5


【解决方案1】:

您将哈希传递给find,而您应该只传递 id。

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

如果您想传递哈希,请使用find_by

@post= Post.find_by(:id => params[:id])

【讨论】:

  • 你有什么before_action吗?
  • 因为有什么奇怪的,你应该在标题之前得到一个错误
  • 这正是您拥有的代码吗?因为您似乎在您的操作中访问标题,而这不是我们所看到的
  • 我没有任何 before_action 是的,这只是我的代码
  • 在这种情况下,除非您在其他地方发现此类错误,否则您应该会收到 ActiveRecord::RecordNotFound 错误
猜你喜欢
  • 2018-08-26
  • 1970-01-01
  • 2019-11-07
  • 1970-01-01
  • 1970-01-01
  • 2022-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多