解决此问题的方法之一是创建一个特殊的操作,用于在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