Rails 名为 has_many 并有限制
我想实现与 ax 条记录的 has_many 关联,并且记录将被命名。
让我们更好地解释一下。在上一个问题中,我问如何使用可选择的标记语言创建一个文本区域,我们得出的结论是,我需要一个单独的模型 Field
,其中包含我需要的多个字段(language
、original
和渲染
)。
现在我希望能够创建一个模型,例如 User
,其中包含其中两个字段。例如:about_me
和 biography
。每次创建用户时如何创建这些字段,在编辑用户时编辑它们并在编辑用户时销毁它们?我如何简单地显示它们:User.about_me
和User.biography
?
预先感谢您的回答。
I want to achieve a has_many association with a x number of records, and the records would be named.
Let's explain that better. In a previous question I asked how to make a text area with a selectable markup language and we reached the conclusion that I needed a separate model, Field
which had the multiple fields I needed (language
, original
and rendered
).
Now I want to be able to make a model, let's say User
, which had two of these fields. For example: about_me
and biography
. How would I create those fields every time I create the user, edit them when I edit the user and destroy them when I edit the user? And how would I display them simply writing: User.about_me
and User.biography
?
Thanks in advance for the answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
David 的解决方案创建了联合模型。
然后您必须在用户表单中包含个人资料的表单。您必须在用户模型中使用 accepts_nested_attributes_for 方法。
要在删除用户时销毁配置文件,请添加
dependent => :destroy
两个模型之间的关系。David's solution creates the joint model.
Then you have to include the form of the profile in the User form. You'll have to use accepts_nested_attributes_for method in the User model.
To destroy the profile when user is deleted, add
dependent => :destroy
to the relationship between the 2 models.您需要使用回调(http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html)。
例如,在您的
User
模型中,有一个 after_create 回调将创建必需的字段。另外,有一个 after_save 回调来检查 user.changed 吗?如果不同,则更新字段。
You'll need to use callbacks (http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html).
For example, in your
User
model, have a after_create callback that will create the requisite fields.Also,have an after_save callback that checks user.changed? and if it is different, update the fields.