我是Ruby on Rails的新手,并尽我所能搜索Stackoverflow和互联网,但仍然难倒。
在我的设置中,评级属于产品和has_many评论。我正在使用简单形式并尝试使用嵌套的fields_for通过评级表单添加RatingComment。有趣的是,当使用单数形式:rating_comment时,会显示该字段。但正如预期的那样,我在尝试保存时遇到了未经许可的参数错误。当我使用复数:rating_comments时,该字段消失。这与此SO posting类似,但将@ rating.rating_comments.build添加到新操作仍然不适用于我。我已经尝试多次重启服务器,甚至重置数据库无济于事。非常感谢任何帮助,因为我过去几天一直在努力解决这个问题。
注意:我还从下面的片段中删除了我认为不相关的代码。如果我需要显示更多信息,请告诉我。提前谢谢!
的routes.rb
resources :ratings, only: [:new, :create, :edit, :update, :destroy] do
resources :rating_comments, shallow: true
end
rating.rb
class Rating < ActiveRecord::Base
belongs_to :product
belongs_to :user
has_many :rating_comments, foreign_key: "rating_id", dependent: :destroy
accepts_nested_attributes_for :rating_comments, reject_if: :all_blank
end
rating_comment.rb
class RatingComment < ActiveRecord::Base
belongs_to :rating
validates :rating_id, presence: true
end
ratings_controller.rb
class RatingsController < ApplicationController
before_action :signed_in_user, only: [:create, :new, :show]
def new
@product = Product.find(params[:id])
@rating = @product.ratings.new
@rating.rating_comments.build
end
def create
@product = Product.find(params[:product_id])
@rating = @product.ratings.build(rating_params)
@rating.user_id = current_user.id
...
private
def rating_params
params.require(:rating).permit(:user_id, :product_id, :rating, rating_comments_attributes: [:rating_id, :content])
end
end
评价/ _new_rating_form.html.erb
<%= simple_form_for([@product, @rating], html: { class: 'form-horizontal' }) do |f| %>
<%= f.error_notification %>
<%= f.input :rating, collection: 1..10, as: :radio_buttons,
item_wrapper_class: 'inline', checked: 5 %>
<%= f.simple_fields_for :rating_comments do |rc| %>
<fieldset>
<%= rc.input :content, label: "Comments" %>
</fieldset>
<% end %>
<%= f.error :base %>
<%= f.button :submit, "Submit" %>
<% end %>
答案 0 :(得分:0)
非常尴尬地承认事实证明我的观点是错误的。一旦我把它放在new.html中,它终于奏效了。