【问题标题】:create creates empty objectscreate 创建空对象
【发布时间】:2017-04-26 11:48:21
【问题描述】:

我试图在保存到数据库之前在 :body 中呈现降价。这是我的创建方法

def create

@post=current_user.posts.create(:title => params[:title],:body => markdown(params[:body])    
redirect_to(post_path(@post))
end

这是我的渲染降价方法

def markdown(text)
options = {
  filter_html:     true,
  hard_wrap:       true,
  link_attributes: { rel: 'nofollow', target: "_blank" },
  space_after_headers: true,
  fenced_code_blocks: true
}

extensions = {
  autolink:           true,
  superscript:        true,
  disable_indented_code_blocks: true
}

renderer = Redcarpet::Render::HTML.new(options)
markdown = Redcarpet::Markdown.new(renderer, extensions)

markdown.render(text).html_safe
end

但是当我输入数据并提交时会生成空对象。

irb(main):001:0> Post.last
Post Load (0.1ms)  SELECT  "posts".* FROM "posts" ORDER BY 
"posts"."id" DESC LIMIT ?  [["LIMIT", 1]]
=> #<Post id: 7, title: nil, body: nil, created_at: "2017-04-26 
11:23:12", updated_at: "2017-04-26 11:23:12", user_id: 1>

我的表格:-

= simple_form_for @post do |f|
 =f.input :title 
 =f.input :body
 =f.button :submit

【问题讨论】:

  • 您确定params[:title]params[:body] 正在返回任何内容吗?您的表单是如何编码的?
  • 用我的表格更新了
  • 首先,如果您不希望使用空白正文内容创建帖子,则可能需要在 Post 模型中的 body 上添加存在验证。
  • title 相同。
  • @JagdeepSingh 我进行了这些更改并修改了 post.rb 现在降价函数抛出错误“错误的参数类型 nil(预期的字符串)”不知何故 params 哈希没有返回字符串

标签: ruby-on-rails ruby activerecord markdown


【解决方案1】:

应该是这样的:

@post=current_user.posts.create(:title => params[:post][:title],:body => markdown(params[:post][:body])    

您可能还想检查Rails StrongParam 以提高安全性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 2021-10-12
    • 2019-07-19
    • 2023-03-10
    • 2014-07-07
    相关资源
    最近更新 更多