2017-04-26 135 views
0

我想在保存到數據庫之前呈現markdown: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 

,但是當我輸入數據並提交空對象genearated。

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 
+0

你確定'params [:title]'和'params [:body]'返回任何內容嗎?你的表單如何編碼? – Babar

+0

用我的表單更新 –

+0

首先,如果您不想使用空白主體內容創建帖子,您可能需要在'Post「模型的'body'中添加一個存在驗證。 –

回答

1

它應該是這樣的:

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

而且你可能想檢查Rails StrongParam以增強安全性。