3

导轨 3.2.3,红宝石 1.9.3p194

尝试使用与 HABTM 关联的子项目保存项目时,我覆盖了默认生成的 SQL,并调用了母项目和每个关联子项目的 Name 属性。如何正确指定关联的子项目名称?#{record.Name},如示例中所示,导致 NameError: undefined local variable or method `record' for #

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}" )} }

有什么建议么?

4

1 回答 1

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}" )} }
于 2012-09-03T15:19:24.560 回答