我的 AdminUser 创建了一项调查以及随之而来的问题。然后另一个用户进行调查。调查将由多个用户进行。调查中的一些问题需要包含该用户的属性(例如:姓名)。所以 AdminUser 会创建一个问题,例如“USER 吃了什么?”但是参加调查的用户会看到“简吃了什么?”。
目前,我有一个调查模型和一个问题模型。我希望调查中的问题包括参与调查的用户姓名。例如,如果问题是“你吃什么?”我希望它能说“Jan 吃什么?”
为了临时完成这项工作,我在我的调查模型上创建了一个方法,每次创建新调查时都会创建新问题。这堵塞了我的数据库,最终相同的问题只有 1 个单词的差异。这也使得将不同用户的答案链接到同一问题变得更加困难,因为每个问题实例都是唯一的。
这是我当前的调查模型
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 you 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 does #{survey_user.first_name} regularly need to avoid?", question_type: "Response", survey_group: "User", survey_group_question_id: 2, choices: "", survey_id: new_survey.id).save
... and so on ...
end
这是我当前的问题模型
class Question < ActiveRecord::Base
belongs_to :survey
end
如您所见,我真的认为我的做法不对。
如何创建可以具有基于其关系之一的动态属性的问题?那可能吗?
我是否需要该属性是带有占位符的静态属性,然后在问题上调用一个方法,在调用时将动态名称插入到占位符中?
我想打电话
Question.new(content: "What does #{survey_user_name} eat?")
Question.new(content: "What does #{survey_user_name} wear?")
我希望将#{name} 替换为调查所有者。因此,同一个问题可以应用于许多不同的调查,并且仍然使用特定调查所有者的姓名。
最佳答案
首先,将 content
列重命名为 content_raw
然后在question
模型中定义一个方法,比如
def content(maybe_some_params)
content_raw.gsub(.....)
end
在这种情况下,如果content_raw
相同,则可以重复使用相同的问题记录
关于ruby-on-rails - 具有基于关系的动态属性值的 Rails 模型实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32102032/