我有后置控制器
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>
答案 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