如何使用动态属性对问卷数据库关系进行建模
我对 Ruby 和 Rails 有点陌生,我试图弄清楚如何使用 Ruby 的动态语言功能来建模以下关系......
该域本质上是一个调查问卷,所以我有用户、问题和答案。
用户有一个 id 和一个名称。答案具有用户 ID 和问题 ID 以及值属性,该值属性是用户对该特定问题的答案。
每个问题都有一个唯一的“代码”,例如,问题可能是“您最喜欢的颜色是什么?”,代码将为“fav_color”。
如果我有一个 User 实例,我希望能够执行以下操作: user.fav_color 来获取/设置此答案。
我想我可以尝试使用 method_missing 然后进行 finder 调用,如下例所示: http://rpheath.com/posts/241-how-to- use-method-missing
或者我可以在运行时向类动态添加属性,如下所示:
但我需要读/写数据库....简单地将这些动态属性存储在实例变量中是不好的为我。
任何帮助将不胜感激...或建议更好的方法来解决这个问题:)
I'm somewhat new to Ruby and Rails and I'm trying to figure out how to model the following relation using Ruby's dynamic language features....
The domain is essentially a questionnaire, so I have Users, Questions, and Answers.
A User has an id and a name. An Answer has a userid and a questionid and a value property which is the user's answer to that particular question.
Each question has a unique 'Code', so for example, a question might be, "What is your favourite color?", and code would be "fav_color".
If I have a User instance, I want to be able to do: user.fav_color to get/set this answer.
I figure I could try and user method_missing and then make a finder call like in this example:
http://rpheath.com/posts/241-how-to-use-method-missing
Or can I dynamically add properties to a class at run-time like here:
Ruby - dynamically add property to class (at runtime)
But I need to read / write to the database....simply storing these dynamic properties in an instance variable is no good for me.
Any help would be much appreciated...or advice on a better way to approach this problem :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我对我的问题提出了以下答案......感谢之前的发帖者(iain),他为我指明了正确的方向。
我对这个解决方案的唯一问题是,如果我向用户展示所有答案,则每个问题都有一个单独的数据库查询。我本以为 :answers 集合只会加载一次......
I've come up with the following answer to my question...thanks to the previous poster (iain) who set me in the right direction.
The only issue I have with this solution is that if I'm showing a user with all answers, there is a separate database query for each question. I would have thought the :answers collection would get loaded only once...