Ruby on rails 使用变量在列名称中循环
我有一个模型方法,它为一个问卷应用程序创建一个报告。表中的每一列代表一个不同的问题,每一行代表一个受访者。它使用column_names方法创建一个问题ID数组,然后添加相关的回答Ruby on rails 使用变量在列名称中循环,ruby-on-rails,ruby,ruby-on-rails-3,Ruby On Rails,Ruby,Ruby On Rails 3,我有一个模型方法,它为一个问卷应用程序创建一个报告。表中的每一列代表一个不同的问题,每一行代表一个受访者。它使用column_names方法创建一个问题ID数组,然后添加相关的回答 def self.import_answers(params) @members = Member.where(:questionnaire_id => params[:questionnaire]) @columns = Report.column_names @members.each do |membe
def self.import_answers(params)
@members = Member.where(:questionnaire_id => params[:questionnaire])
@columns = Report.column_names
@members.each do |member|
@report = Report.find_by_membership_number(member.membership_number)
@responses = Response.where(:member_id => member.id)
@columns.each do |column|
question = column.to_s.gsub("q", "").to_i
@response = @responses.where(:question_id => question).first
unless @response.nil?
@report.column = @response.response_id
@report.save
end
end
end
结束
此方法在@report.column行中断
我认为这可能是因为column_names方法返回一个字符串数组,如下所示
["q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10"]
这意味着@report.column行的迭代如下
@report."q1"
相对于
@report.q1
这很有效
我可能错了!但不管怎样,我正在努力想办法让它工作,任何帮助都将不胜感激 @report.send(“#{column}=”.to_sym,@response.response_id)
@report.send(column.to_sym) = @response.response_id
您可以获得更多信息。您可以使用send(“#{atr}=”)
动态设置属性。查看代码后,最好使用update\u属性
,因为它在一次调用中执行set
和save
操作
我还注意到您在模型之外有一个问题id
提取逻辑。最好将其封装在报表模型中
class Report < ActiveRecord::Base
# extract the question id from the column
def self.column_question_id(name)
name[1..-1].to_i
end
end
您不显示定义
@report
的位置。另外,您可以添加发生的确切错误吗?仅仅报告它坏了太含糊不清了。你期待什么结果?您是否希望@report
将是一个包含一系列问题和回答的受访者数组?reports表为每个成员创建一行@报表引用表中的行(成员)。我已经更新了我的问题以显示完整的方法。是的!这是非常有效的。虽然update_属性拼写确实需要额外的T,但我不会因此对您不利。成堆的感谢,滴答!
Report.column_names do |column|
@response = @responses.find_by_question_id(Report.column_question_id(column))
@report.update_attribute(column, @response.response_id) if @response.present?
end