create與show在不同的model
2012-03-19 16:02:33 +0800 由 chiayi
在 Ruby on Rails 節點 中發起
最後由 chiayi 於2012-03-20 22:07:08 +0800回應
, 280次閱讀
最近用了acts_as_commentable,為了很多地方都都可以用comment的機制
參考了這篇文章http://www.arailsdemo.com/posts/16
之所以會參考這篇文章是因為,它把create都交給comments controller,而show的動作給commentable controller,create完成後它依據不同commentable的class name動態去決定要去render哪一個controller action。
目前遇到的問題是在create完成後,可能會發生validate失敗,所以要render commentable show action,而不是comment show action,在程式碼中,不知為何它始終無法render正確的controller,即使我直接在create action失敗後寫render "posts/show"也沒用。
補充:render的目的是要顯示validate失敗的原因,就如同慣例。
# app/controllers/posts_controller.rb
def render_error_page
model_name = @commentable.class.name
instance_variable_set("@#{model_name.downcase}", @commentable)
render "#{model_name.underscore.downcase.pluralize}/show" # This is "posts/show"
end
雖然也可以在client端validate,但作者設計的這個方式挺好的
不知會不會是rails的版本不同,畢竟那篇文章是2010年的
請問有人有解嗎?謝謝