2012-08-31 109 views
3

的Rails 3.2.3,紅寶石1.9.3p194HABTM-協會INSERT_SQL

試圖保存HABTM相關子項目項目,我覆蓋默認生成的SQL,以調用母親項目和每一個相關的名稱屬性子項目。如何正確指定關聯的子項目名稱? #{} record.Name,作爲例子,導致 NameError:對#

has_and_belongs_to_many :subproject, :class_name => "Project", 
:join_table => "project_subproject", :foreign_key => "projectname", :association_foreign_key => "subprojectname", 
:finder_sql => proc { %{SELECT `project`.* FROM `project` INNER JOIN `project_subproject` ON `project`.`name` = `project_subproject`.`subprojectname` WHERE `project_subproject`.`projectname` = '#{self.Name}' } }, 
#TODO: find correct expression for insert sql 
:insert_sql => proc { %{INSERT INTO `project_subproject` (`projectname`, `subprojectname`) VALUES ("#{self.Name}","#{record.Name}")} } 

任何建議 未定義的局部變量或方法'記錄」?

回答

5

解決了,來自Rails 3.1。發行說明:

以前:has_and_belongs_to_many關聯中的insert_sql和:delete_sql允許您調用'record'來獲取插入或刪除的記錄。這現在作爲參數傳遞給proc。

因此:

:insert_sql => proc { |record| %{INSERT INTO `project_subproject` (`projectname`, `subprojectname`) VALUES ("#{self.Name}","#{record.Name}")} }