【问题标题】:rails how to use Associated Model with the admin namespacerails 如何将关联模型与管理命名空间一起使用
【发布时间】:2018-03-19 15:06:47
【问题描述】:

感谢我可以在这里提问。我正在使用带有 ruby​​ 2.5.0 的 rails 5.1.4。 我有两个模型,模型 A 和模型 B。

    Model A has_many bs
    Model B belongs_to a

管理员用户可以生成新的 a 条目,也可以生成新的 b 条目。 no-admin-user 可以显示、索引或保留。

routes.rb

    resources :as, only: [:index, :show] do
      resources :bs, only: [:index, :show, :reserve]
    end
    namespace :admin do
     resources :as, only: [:create, :edit, :update, :destroy,  
       :show] do
       member do
         post :activate
         get :activate
         post :deactivate
         get :deactivate
       end
     resources :bs, only: [:create, :edit, :update, :destroy, :show]
    end
  end

app/views/admin/as/show.html.erb 中,您可以看到a 的DB 条目的值。所以现在我的想法是意识到您可以使用表单添加 b 的新 B 条目。我试过这个 show.html.erb

show.html.erb

    <h2><%=t("show")%></h2>
    <p>
      <strong><%=t("title")%></strong>
      <%= @a.title %>
    </p>
    <p>
      <strong><%=t("description")%></strong>
      <%= @a.description %>
    </p>
    <p>
      <strong><%=t("email")%>:</strong>
      <%= @a.email %>
    </p>
    <h2><%=t("entries")%></h2>
    <%= render @a.bs %>
    <h2><%=t("addentry")%></h2>
    <%= form_with(model: [ @a, @admin.bs.build ], local: true) do |f| %>
    <p>
      <%= f.label :title %><br>
      <%= f.text_field :title %>
    </p>
    <p>
      <%= f.label :description %><br>
      <%= f.text_area :description %>
    </p>
    <p>
      <%= f.submit %>
    </p>

将生成表单,但 html-sourcecode 不显示“admin-route-path”。但是我该怎么做呢?

   <form action="/as/1/bs" accept-charset="UTF-8" method="post"

如何更改 form_with 部分,以便我可以从 b 将条目添加到关联模型中?

【问题讨论】:

标签: ruby-on-rails ruby database web-development-server


【解决方案1】:

您似乎希望您的表单访问 URL /admin/as/bs。 要构建到命名空间控制器的链接,您可以使用以下表单:

link_to [:admin, @a, @b], 'A admin show'
link_to admin_as_bs_path(@a, @b), 'A admin show'

同样适用于表单

form_for [:admin, @a, @b] do ...
form_for @a, url: admin_as_bs_path(@a, @b)

路由助手的名称可能有误。检查rake routes 的输出。

【讨论】:

  • 我想点击/admin/as/id/bs 来创建一个新的bs条目
  • 如果您尝试该指南,它可以正常工作,但没有管理员命名空间。
  • 现在我找到了解决方案的下一步。我正在使用 form_with,因为 form_for 已被软性弃用。 &lt;%= form_with(model: [:admin, @a ]) do |f| %&gt; 这构建了 url form action="/admin/a/id" accept-charset="UTF-8" method="post"&gt; 但是我如何获得 url 中的 bs。这是关于 stackverflow 的额外问题吗?
【解决方案2】:

要获得您正在寻找的路线,您需要有嵌套资源。你可以找到一个很好的解释here

【讨论】:

    【解决方案3】:

    我找到了相关模型的解决方案,它工作正常。谁能证实这一点。谢谢

    <%= form_with(model: [:admin, @a,B.new ], local: true) do |f| %> <% end %>

    【讨论】:

      猜你喜欢
      • 2019-01-29
      • 1970-01-01
      • 2015-04-05
      • 2013-05-28
      • 1970-01-01
      • 2023-03-12
      • 2012-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多