如何使用嵌套属性进行评分

时间:2018-08-13 04:57:29

标签: ruby-on-rails nested-attributes

我有后置控制器

def show
  @post = @topic.posts.find(params[:id])
  @rate=@post.ratings.all
  @post.ratings.build
  @rate = Rating.where(post_id: @post.id).group("rate").count
end

private 
def post_params
  params.require(:post).permit(:title, :body, :topic_id, tags_attributes: [:tagname], tag_ids: [], ratings_attribute: [:rate])
end

post.rb

 class Post < ApplicationRecord
   has_many :ratings,dependent: :destroy
   accepts_nested_attributes_for :ratings
 end

rating.rb

class Rating < ApplicationRecord
  belongs_to :post
  validates_presence_of :rate
end

show.html

   <div class="container" >
    <h3 class="mt-5"><b><%= @topic.topicname %> Post </b></h3><hr>
     <div class="well">
    <h4><strong>Title : </strong><%= @post.title %></h4><hr>
    <h4><strong>Body : </strong><%= @post.body %></h4>
    </div>
    <%= render 'tags/tags' %>
    <h3>Ratings:</h3>
    <%= form_for [@topic, @post] do |f| %>
    <%= f.fields_for :ratings, @post.ratings.build do |builder| %>
      <fieldset>
        <% for i in 1..5 %>
          <%= builder.radio_button :rate, i %><%= i %>
        <% end %>
      </fieldset>
    <% end %>
    <%=f.submit  %>
   <% end %>
      <% if @rate.present? %>
      <% @rate.each do |k, v| %>
      <% t = k %>
      <% for i in 1..t%>
      <span class="fa fa-star checked"></span>
      <% end %>
      <%t=t+1 %>
      <%= v %><br>
    <% end %>
     <% end %>
  <div class="row" >
    <div class="col-md-6">
      <%= render 'comments/comments' %>
    </div>
    <div class="col-md-6">
      <%= render 'comments/form', object: @post %>
    </div>
  </div>
</div>
在这个项目中,我需要使用等级作为帖子模型中的嵌套属性,并在帖子的显示页面中使用字段集,我想使用单选按钮为正在查看的帖子提供等级。我的问题是,当我使用单选按钮给评分时,费率值未插入数据库。

1 个答案:

答案 0 :(得分:0)

事实证明,您在ratings_attribute(s)末尾的允许参数中缺少“ s”。将您的方法post_params更改为:

def post_params
  params.require(:post)
        .permit(:title, :body, :topic_id,
                tags_attributes: [:tagname],
                tag_ids: [],
                ratings_attributes: [:rate])
end