create创建空对象

时间:2017-04-26 11:48:22

标签: ruby-on-rails ruby activerecord markdown

我想在保存到数据库之前在body中渲染markdown。这是我的创建方法

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

1 个答案:

答案 0 :(得分:1)

应该是这样的:

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

此外,您可能希望检查Rails StrongParam以增强安全性。