【问题标题】:Ruby on rails nested form modelRuby on rails 嵌套表单模型
【发布时间】:2011-01-11 23:35:05
【问题描述】:

我正在尝试使用 rails 嵌套的 form_for 助手,但出现以下错误:

BlogPage(#49859550) 预期,得到 Array(#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:

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 框架还是很陌生,无法通过谷歌搜索自己解决问题。

谢谢。

【问题讨论】:

  • 您应该在代码中出现错误的地方添加行号和注释。如果@blog.save 成功,您还应该重定向。现在的方式,刷新浏览器可能会导致插入重复记录。需要 'pp' 并使用 'raise @blog.pretty_inspect' 来查看你有什么样的数组。
  • 谢谢。我添加了您推荐的一些建议。添加 require 'pp' 有什么作用?

标签: ruby-on-rails actionview actioncontroller


【解决方案1】:

【讨论】:

  • 感谢您的链接。我不确定我是否应该再使用这种方法,因为似乎使用不与模型嵌套的 field_for 并在控制器中添加一些逻辑会更容易。
【解决方案2】:

将您的表单更改为:

<% 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。但是我不确定这是否会导致错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多