0

ruby のネストされたモデルを掘り下げているときに、問題が発生しました。

次のシナリオを考えてみましょう。

私は次のモデルを持っています:

  • 著者

以下の仕様:

著者:

class Author < ActiveRecord::Base
  attr_accessible :name
  has_many :books, dependent: :destroy

  accepts_nested_attributes_for :books #I read this is necessary here: http://stackoverflow.com/questions/12300619/models-and-nested-forms

  # and some validations...
end

本:

class Book < ActiveRecord::Base
  attr_accessible :author_id, :name, :year
  belongs_to :author

  #and some more validations...
end

著者に本を追加したいと思います。ここに私のauthors_controllerがあります:

def new_book
  @author = Author.find(params[:id])
end

def create_book
  @author = Author.find(params[:id])
  if @author.books.create(params[:book]).save
    redirect_to action: :show
  else
    render :new_book
  end
end

そして、これは私がそれをやろうとするフォームです:

<h1>Add new book to <%= @author.name %>'s collection</h1>
<%= form_for @author, html: { class: "well" } do |f| %>
    <%= fields_for :books do |b| %>
        <%= b.label :name %>
        <%= b.text_field :name %>
        <br/>
        <%= b.label :year %>
        <%= b.number_field :year %>
    <% end %>
    <br/>
    <%= f.submit "Submit", class: "btn btn-primary" %>
    <%= f.button "Reset", type: :reset, class: "btn btn-danger" %>
<% end %>

問題: データを入力して [送信] をクリックすると、正しい作成者にリダイレクトされますが、その作成者の新しいレコードは保存されません。多くの調査の後、ここで間違っていることを見つけることができないようです。

4

3 に答える 3

1

authors_controllerを次のように変更します。

def new_book
  @author = Author.find(params[:id])
  @book = Book.new
end

あなたのフォーム:

<h1>Add new book to <%= @author.name %>'s collection</h1>
<%= form_for ([@author, @book]), html: { class: "well" } do |f| %>

そして、routes.rb

resources :authors do
  resources :books
end  
于 2012-10-18T20:43:53.960 に答える
1

:nested_attributes_for_booksAuthor モデルにアクセス可能なメソッドを追加する必要もあります。Author コントローラーの create メソッドは、コードを追加する必要はありません。

注:成功時に「books#show」をレンダリングするように Books コントローラーを設定します。アプリがユーザーを著者にリダイレクトしている場合、本ではなく著者にリダイレクトするように設定しない限り、著者コントローラが本の作成を処理していることを意味します。

于 2012-10-18T21:35:26.247 に答える
1

あなたはいくつかのことを見逃しています。

コントローラ:

...
def new_book
  @author = Author.find(params[:id])
  @author.books.build
end
...

ビュー、それf.fields_forだけではありませんfields_for

<%= f.fields_for :books do |b| %>
  <%= b.label :name %>
  <%= b.text_field :name %>
  <br/>
  <%= b.label :year %>
  <%= b.number_field :year %>
<% end %>
于 2012-10-18T20:54:33.973 に答える