Rails 3.2.3,Ruby 1.9.3p194
尝试使用与HABTM相关的子项目保存项目时,我会覆盖默认生成的SQL,并调用母项目的Name属性和每个关联的子项目。如何正确指定关联的子项目名称? #{record.Name},如示例所示,导致 NameError: 未定义的局部变量或#
的方法`record'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}" )} }
任何建议?
答案 0 :(得分: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}" )} }