本文介绍了accepts_nested_attributes_for导致SQLException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用accepts_nested_attributes_for创建一个has_many节的Article对象.

I would like to use accepts_nested_attributes_for to create an Article object that has_many Sections.

class Article < ActiveRecord::Base
  has_many :sections, :order => "position", :dependent => :destroy
  belongs_to :categories
  accepts_nested_attributes_for :sections, :allow_destroy => true, :reject_if => lambda { |attributes| attributes['title'].blank? }
  validates_presence_of :name, :on => :create, :message => "An article must have a title"
end

class Section < ActiveRecord::Base
  belongs_to :article
  acts_as_list :scope => "article"
  has_attached_file :image,
                    :styles => { :medium => "300x300>",
                                 :thumb => "100x100>" }
end

无论:reject_if条件何时接受嵌套属性(如果title属性不是blank?),我都会看到SQLException.否则,将成功创建没有相关章节的文章.

Whenever the :reject_if condition accepts the nested attribute (if the title attribute is not blank?) I see a SQLException. Otherwise the Article will be created successfully without the associated Sections.

Parameters: {"article"=>{"name"=>"My Article", "category_id"=>"7", "sections_attributes"=>{"0"=>{"title"=>"Section 1", "content"=>"Section 1 of my new article"}}}}

AREL (30.3ms)  INSERT INTO "articles" ("content", "category_id", "position", "name") VALUES (NULL, 7, NULL, 'My Article')

Section Load (0.4ms)  SELECT "sections".* FROM "sections" WHERE (article) ORDER BY position DESC LIMIT 1

SQLite3::SQLException: no such column: article: SELECT "sections".* FROM "sections" WHERE (article) ORDER BY position DESC LIMIT 1
Completed   in 68ms

我试图找出在Section Load阶段出了什么问题,因为WHERE (article)是意外的.感谢您的阅读.

I'm trying to figure out what's going wrong during the Section Load stage, since WHERE (article) is unexpected. Thanks for reading.

推荐答案

按照 acts_as_list文档(如果提供了字符串),则gem认为它是SQL,它将按字面意义使用.您想在这里使用:article-告诉acts_as_list使用:article关联.

Your problem here is your acts_as_list :scope => "article" call, as per the acts_as_list docs if you provide a string, then the gem considers that to be SQL which it will use literally. You wanted to use :article here - which tells acts_as_list to use the :article association.

这篇关于accepts_nested_attributes_for导致SQLException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 23:10