Rails不保存具有多态模型的嵌套表单

时间:2015-01-31 23:08:40

标签: ruby-on-rails ruby-on-rails-4

我有这些模特:

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

我做错了什么?谢谢。

1 个答案:

答案 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 %>