Rails 嵌套资源和初始化资源的路由

发布于 2025-01-08 14:02:47 字数 609 浏览 3 评论 0原文

当使用嵌套表单/资源和路由时,我对 Rails 的正常运行方式有疑问。

我有两个表,单词和定义...

单词有很多定义,但我不会创建单词,直到它至少有一个定义。

模型和控制器端的所有内容都有效,但我无法弄清楚如何处理表单助手。

<%= semantic_form_for [@word, @definition] do |f| %>

这很有效,但前提是 @word 确实存在并且不是新的未保存记录。在控制器中的 IE 中,我正在对 Word 进行 find_or_initialize_by 调用,然后根据该调用构建定义。

<%= semantic_form_for [:word, @definition] do |f| %>

此词但仅当该词不存在时才会出现。 IE 如果我尝试使用这种结构进行编辑,我会得到一个奇怪的 url(这不起作用)。 words/12345/definition/12345

我尝试使用 url_for 帮助器,但得到了与上面类似的结果...

还有其他想法吗?

I have a problem with the normal way rails operates when using nested forms / resources and routing.

I have two tables, Words and Definitions...

Words have many definitions, but I do not create a Word until it has at least one definition.

Everything on the model and controller end works but I cannot figure out how to handle the form helpers.

<%= semantic_form_for [@word, @definition] do |f| %>

This works perfectly but only if @word actually exists and is not a new UNSAVED record. IE in the controller I am doing a find_or_initialize_by call for Word then building a definition off of that.

<%= semantic_form_for [:word, @definition] do |f| %>

This words but only if the word doesn't exist. IE if I try to edit using this construction I get an odd url (which doesn't work). words/12345/definition/12345

I tried using the url_for helper but had similar results as above...

Any other ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

握住你手 2025-01-15 14:02:47

默认情况下,Mongoid 不会初始化嵌入文档。您最有可能需要通过 Word 模型中的回调自行构建它们:

after_initialize :build_definition

def build_definition
  self.definitions.build unless self.definitions.any?
end

Mongoid doesn't initialize embedded documents by default. You need to build them yourself most likely with a callback in your Word model:

after_initialize :build_definition

def build_definition
  self.definitions.build unless self.definitions.any?
end
带刺的爱情 2025-01-15 14:02:47

如果你想保持 CRUD 并允许在单词之前创建定义,则必须复制定义的路由,一个在单词内部,一个在单词外部,所以你可以这样做:

<%= semantic_form_for [@definition] do |f| %>

If you wanna stay CRUD and allow definitions to be created before words, you must duplicate routes for definitions, one inside words and one outside, so you can do:

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