Rails 名为 has_many 并有限制

发布于 2024-10-11 07:23:33 字数 547 浏览 8 评论 0原文

我想实现与 ax 条记录的 has_many 关联,并且记录将被命名。

让我们更好地解释一下。在上一个问题中,我问如何使用可选择的标记语言创建一个文本区域,我们得出的结论是,我需要一个单独的模型 Field,其中包含我需要的多个字段(languageoriginal渲染)。

现在我希望能够创建一个模型,例如 User,其中包含其中两个字段。例如:about_mebiography。每次创建用户时如何创建这些字段,在编辑用户时编辑它们并在编辑用户时销毁它们?我如何简单地显示它们:User.about_meUser.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

っ〆星空下的拥抱 2024-10-18 07:23:33

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.

睫毛溺水了 2024-10-18 07:23:33

您需要使用回调(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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文