Reputation: 2211
I have a model method, which creates a report for a questionnaire app. Each column in the table represents a different question, and each row is an interviewee. It uses the column_names method to create an array of question ids, and then add the relevant responses.
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
end
This method breaks at the line @report.column.
I think it could be because the column_names method returns an array of strings, like so...
["q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10"]
This means that the line @report.column iterates like
@report."q1"
as opposed to...
@report.q1
which works.
I could be wrong about that! But either way, I am struggling to figure out how I can get it to work, any help would be much appreciated!
Upvotes: 0
Views: 241
Reputation: 64373
You can use send("#{atr}=")
to dynamically set an attribute. After reviewing your code you might be better off using update_attribute
as it performs the set
and save
operations in one call.
I also noticed that you have the question id
extraction logic outside the model. It might be better to encapsulate it in the Report model.
class Report < ActiveRecord::Base
# extract the question id from the column
def self.column_question_id(name)
name[1..-1].to_i
end
end
Now your code can be written as:
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
Upvotes: 1