Модель вложенной формы Ruby on rails - PullRequest
1 голос
/ 02 февраля 2010

Я пытаюсь использовать rails nested 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 %>

Вот параметры, которые отправляются на контроллер:

{ "совершить" => "Сохранить", "blog" => {"blog_pages" => {"content" => "Это новое содержимое записей блога."}, "title" => "Это новая запись в блоге.", "Завершить" => "1"}, "Authenticity_token" => "T1Pr1g9e2AjEMyjtMjLi / ocrDLXzlw6meWoLW5LvFzc ="}

Вот BlogsController с выполняемым действием create:

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

Если кто-нибудь сможет мне помочь с этим, я буду очень признателен. Я все еще довольно новичок в ruby ​​и rails Framework и не могу решить проблему самостоятельно, прибегая к помощи.

Спасибо.

Ответы [ 2 ]

2 голосов
/ 02 февраля 2010
0 голосов
/ 03 февраля 2010

Измените свою форму на это:

<% 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, он автоматически перебирает страницы блога. Однако я не уверен, что это вызвало ошибки.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...