Ruby on rails 在同一控制器中添加评级和注释
我已经得到了一个基于RailsCast238的评论模型,但我也想添加投票和评级 我当前的文章控制器显示为:Ruby on rails 在同一控制器中添加评级和注释,ruby-on-rails,mongoid,polymorphic-associations,rating,railscasts,Ruby On Rails,Mongoid,Polymorphic Associations,Rating,Railscasts,我已经得到了一个基于RailsCast238的评论模型,但我也想添加投票和评级 我当前的文章控制器显示为: def show @article = Article.find(params[:id]) @commentable = @article @comments = @commentable.comments @comment = Comment.new respond_to do |format| format.html # sho
def show
@article = Article.find(params[:id])
@commentable = @article
@comments = @commentable.comments
@comment = Comment.new
respond_to do |format|
format.html # show.html.erb
format.json { render json: @article }
end
end
我曾尝试复制相同的流程并添加应课差饷租值,但我不知道如何将其整合到表演中。我曾考虑过从application controller创建一个通用函数,然后尝试将其分配到show函数中的多个对象(newb),但这似乎过于复杂了
我试着加上:
@rateable = @article
@ratings = @rateable.ratings
@rating = Rating.new
它不起作用。但现在我想如果我把它分配给
@ratings = Article.find(params[:id]}
@ratings = @rateable.ratings
@rating = Rating.new
即使这样做有效,也必须有更干净的方法来做到这一点
编辑:
此代码行更正后出错,与工作注释版本相同
<%= form_for [@rateable, @rating] do |f| %>
<% if @rating.errors.any? %>
<div class="error_messages">
<h2>Please correct the following errors.</h2>
<ul>
<% @rating.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.text_area :content, rows: 8 %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
请更正以下错误。
好吧,我想我明白了。只需将
更改为:
<%= f.submit 'Submit', { controller: 'ratings', action: 'create', method: 'post' } %>
在您的routes.rb
文件中,您还需要put'/ratings/create'=>“ratings”#create'
或干脆resources:ratings
这将把你的表单发送到
评级#创建,我认为这是你想要的。你只需要参数@rateable
,@ratings
,和@rating
都可以在show
视图中使用。另外,为什么要设置@commentable=@article
和@rateable=@article
?为什么不直接参考@article
?当我这样做时,我得到了未定义的方法文章\u评级\u路径'
,我几乎偏离了这一点,不知道如何向混合中添加另一个对象。第一个问题的答案是肯定的。哦,好吧,你可以将问题中的第二块代码添加到show
方法中,这些变量也将在你的视图中可用。我注意到你说过这样做“不起作用”。如果没有,我需要查看错误消息。另外,为什么要将respond_to
块添加到show
方法的版本中?在json响应中,您提到了@articlei
这是一个打字错误吗?这和更改路线以包含评级是一个胜利!