ruby - Rails model instance with dynamic attribute value based on relationship -
my adminuser creates survey , questions go along it. different user takes survey. survey taken multiple users. of questions in survey, need include attribute of user (example: name). adminuser create question "what did user eat?" user takes survey see "what did jane eat?".
currently, have survey model , question model. questions in survey include user's name taking survey. example, if question "what eat?" "what jan eat?"
to temporarily accomplish created method on survey model creates new questions each time new survey created. clogging database same questions 1 word difference. makes more difficult link different users' answers same question since each question instance unique.
here current survey model
survey.rb
class survey < activerecord::base belongs_to :user belongs_to :surveyable, :polymorphic => true has_many :questions, :dependent => :destroy def self.generate_for_user(survey_user) new_survey = survey.new new_survey.surveyable_id = survey_user.id new_survey.surveyable_type = "user" new_survey.user = client new_survey.save question.new(position: 1, tier: 1, content: "when did first become aware of #{survey_user.first_name}'s needs?", question_type: "response", survey_group: "user", survey_group_question_id: 1, choices: "", survey_id: new_survey.id).save question.new(position: 2, tier: 1, content: "what foods #{survey_user.first_name} regularly need avoid?", question_type: "response", survey_group: "user", survey_group_question_id: 2, choices: "", survey_id: new_survey.id).save ... , on ... end
here current question model
class question < activerecord::base belongs_to :survey end
as can see, dont think went right way.
how can create questions can have dynamic attribute based on 1 of relationships? possible?
do need attribute static placeholder , call method on question inserts dynamic name placeholder when called?
i able call
question.new(content: "what #{survey_user_name} eat?") question.new(content: "what #{survey_user_name} wear?")
and want #{name} replaced survey owner. same question can applied many different surveys , still use specific survey owners name.
first, rename content
column content_raw
then define method in question
model,
def content(maybe_some_params) content_raw.gsub(.....) end
in case, can reuse same question record if content_raw
same
Comments
Post a Comment