1

form_for helperにネストされたレールを使用しようとしていますが、次のエラーが発生します。

BlogPage(#49859550)が必要です、配列を取得しました(#31117360)

これが私のモデルオブジェクトです:

class Blog < ActiveRecord::Base
  # Table Configuration
  set_table_name "blog"

 # Model Configuration
 belongs_to :item
 has_many :blog_pages
 accepts_nested_attributes_for :blog_pages, :allow_destroy => true
end

class BlogPage < ActiveRecord::Base
  # Table Configuration
  set_table_name "blog_page"

  # Model Configuration
  belongs_to :blog
end

これが私が生成したフォームです(不要なHTMLを省略しました):

<% form_for :blog, :url => { :action => :create } do |blog_form| %>  
    <%= blog_form.text_field :title, :style => "width: 400px" %>  
    <% blog_form.fields_for :blog_pages do |page_fields| %>
        <% @blog.blog_pages.each do |page| %>  
            <%= page_fields.text_area :content, :style => "width: 100%",
                :cols => "10", :rows => "20" %>
        <% end %>
    <% end %>
<% end %>

コントローラに送信されるパラメータは次のとおりです。

{"commit" => "Save"、 "blog" => {"blog_pages" => {"content" => "これは新しいブログエントリのコンテンツです。"}、 "title"=>"これは新しいブログですentry。"、" complete "=>" 1 "}、" authenticity_token "=>" T1Pr1g9e2AjEMyjtMjLi / ocrDLXzlw6meWoLW5LvFzc = "}

実行されるcreateアクションを持つBlogsControllerは次のとおりです。

class BlogsController < ApplicationController
  def new
    @blog = Blog.new # This is the line where the error gets thrown.  
    # Set up a page for the new blog so the view is displayed properly.
    @blog.blog_pages[0] = BlogPage.new
    @blog.blog_pages[0].page_number = 1
    respond_to do |format|
      format.html # Goes to the new.html.erb view.
      format.xml { render :xml => @blog }
      format.js { render :layout => false}
    end
  end

  def create
    @blog = Blog.new(params[:blog])

    respond_to do |format|
      if @blog.save
        render :action => :show
      else
        flash[:notice] = "Error occurred while saving the blog entry."
        render :action => :new
      end
    end
  end
end

誰かがこれで私を助けることができるならば、私はそれを大いに感謝します。私はまだルビーとレールフレームワークにかなり慣れておらず、グーグルで問題を自分で解決することはできませんでした。

ありがとう。

4

2 に答える 2

2

これを見たことがありますか?

http://media.pragprog.com/titles/fr_arr/multiple_models_one_form.pdf

于 2010-02-02T01:12:14.273 に答える
0

フォームを次のように変更します。

<% form_for :blog, :url => { :action => :create } do |blog_form| %>  
    <%= blog_form.text_field :title, :style => "width: 400px" %>  
    <% blog_form.fields_for :blog_pages do |page_fields| %>
            <%= page_fields.text_area :content, :style => "width: 100%",
                :cols => "10", :rows => "20" %>
    <% end %>
<% end %>

使用する場合fields_for、blog_pages を自動的に反復処理します。ただし、これがエラーを引き起こしたかどうかはわかりません。

于 2010-02-02T22:44:34.587 に答える