1
我發現自己試圖實現一個不完美的解決方案,以不破壞現有的代碼。從Rails中的幫助器方法捕獲HTML輸出
我有在Rails輔助類的現有的輔助方法,其選擇性地呈現基於參數幾個泛音之一:
def render_widget_container(thingy)
if thingy.is_awesome?
render(partial: 'thingies/awesome', locals: {thingy: thingy })
elsif thingy.sucks?
render(partial: 'thingies/sucky', locals: {thingy: thingy })
end
end
在控制器,我想捕獲從這個輔助的輸出,並且把它作爲其中一個值在JSON哈希像這樣:
@thingy = Thingy.find(params[:id])
respond_to do |format|
format.json {
{:name => "thingy 1", :html => render_widget_container(thingy) }
}
end
我曾嘗試與這些結果如下:
render_widget_container(thingy)
Render and/or redirect were called multiple times in this action.
capture(render_widget_container(thingy))
(eval):1: syntax error, unexpected $undefined $["<div id=\"video_container\"... ^ (eval):1: syntax error, unexpected ']', expecting $end ...r'></div>\n </div>\n</div>\n"] = ["<DIV ID=\"VIDEO_CONTAINE... ...
capture(render_to_string(render_widget_container(thingy)))
*SHIT TON OF ESCAPED HTML* is not an ActiveModel-compatible object that returns a valid partial path.
問題擱置關於爲什麼你會想要做這樣的事情,我將如何去從我的控制器內部從我的幫手捕獲生成的HTML?
也許你想使用「render_to_string」? (http://stackoverflow.com/questions/13713250/render-to-string-partial-format-error-in-controller) – MrYoshiji