我有这些模特:
class Review < ActiveRecord::Base
belongs_to :reviewable, polymorphic: true
end
class Article < ActiveRecord::Base
has_one :review, as: :reviewable, dependent: :destroy
accepts_nested_attributes_for :review
end
这样的形式:
<%= form_for @article do |f| %>
<%= f.fields_for(:review, Review.new) do |r| %>
<%= r.label :content %>
<%= r.text_field :content %>
<% end %>
<%= f.label :description %>
<%= f.text_field :description %>
<% end %>
在我的ArticlesController
内,我创建了这样简单的文章:
@article = Article.new(article_params)
@article.save
def article_params
params.require(:article).permit(:description, review_attributes: [:id, :content])
end
我做错了什么?谢谢。
答案 0 :(得分:1)
尝试添加accepts_nested_attributes_for
<强>更新强>
应用/模型/ article.rb 强>
class Article < ActiveRecord::Base
has_one :review, as: :reviewable, dependent: :destroy
accepts_nested_attributes_for :review
end
应用/控制器/ articles_controller.rb 强>
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article, notice: "Article created!"
else
render :new
end
end
private
def article_params
params.require(:article).permit(:description, review_attributes: [:content])
end
查看强>
<%= form_for(@article) do |form| %>
<%= form.fields_for(:review_attributes, @article.build_review) do |review| %>
<%= review.label :content %>
<%= review.text_field :content %>
<% end %>
<%= form.label :description %>
<%= form.text_field :description %>
<% end %>