解決此問題的方法之一是創建一個特殊的操作,用於在PublicationsController
和其他可評論的控制器中創建註釋(您可能希望創建一個模塊,您將包含在所有可評論的控制器中以避免重複和干涉碼)。
我沒有時間檢查測試Rails應用程序,所以我可能犯了一些錯別字或其他錯誤,或忘記了上面代碼中的某些內容。不過,我希望,這個想法很明確。如果發現錯誤,隨意編輯。
在你PublicationsController
(和其他commentable控制器):
def add_comment
# PublicationsController -> Publication
@commentable_class = self.class.to_s[0..-11].singularize.constantize
@commentable = @commentable_class.find(params[:commentable_id]) # it is passed by the form, see below
# set @publication for the publication-specific part of the show view
instance_variable_set('@'[email protected]_class.to_s.underscore, @commentable)
@comment = Comment.new(comment_params.merge(commentable: @commentable))
if @comment.save
redirect_to action: :show, anchor: 'comment-' + @comment.id.to_s
else
render action: :show
end
end
...
def comment_params
# don't forget to define comment_params - as in CommentsController, I guess:
params.require(:comment).permit(:author,:subject,:message)
end
在這些commentable控制器的show
行動只是做
def show
...
@commentable_class = self.class.to_s[0..-11].singularize.constantize
@comment = Comment.new
@commentable = instance_variable_get('@'[email protected]_class.to_s.underscore)
...
end
在show
視圖的commentables使用類似以下添加新評論的形式(基於提供的要點):
- if @comment.errors.any?
%section.errors
%p= t('errors.templates.body')
%ul
- @comment.errors.full_messages.each do |message|
%li= message
= form_for @comment, url: {controller: @commentable_controller, action: :add_comment} do |form|
= hidden_field_tag 'commentable_id', @commentable.id
- unless user_signed_in?
.row
.small-12.columns
= form.label :author
= form.text_field :author, required: true, pattern: '.{3,30}', title: t('errors.messages.not_in_between', from: 3, to: 30)
.row
.small-12.columns
= form.label :subject
= form.text_field :subject, pattern: '.{5,80}', title: t('errors.messages.not_in_between', from: 5, to: 80)
.row
.small-12.columns
= form.label :message
= form.text_area :message, required: true, pattern: '.{30,5000}', title: t('errors.messages.not_in_between', from: 30, to: 5000)
= form.submit class: 'small radius button right'
您的出版物/展示視圖(以及其他可評論的展示視圖)的外觀如何?我對顯示「評論表」的部分感興趣。 – moonfly 2014-10-10 23:00:00
這裏我們去:https://gist.github.com/openscript/37c497bec47141d845dd – Robin 2014-10-11 09:39:45
所以,你已經在'comments/form'部分有'@ comment'了,甚至還有'@comment.errors.full_messages.each。 ..'裏面。你如何在'PublicationsController'和其他控制器中創建'@ comment'來評論?看起來你需要將URL參數中的@ comment屬性傳遞給'redirect_to controller:@ comment.commentable,action::show'以防錯誤發生,並從params []中選擇它。 – moonfly 2014-10-11 15:00:34