rails how to use Associated Model with the admin namespace

允我心安 提交于 2019-12-09 03:52:37

问题


thanks that i can ask questions here. I'm using rails 5.1.4 with ruby 2.5.0. I have two models the model A and Model B.

    Model A has_many bs
    Model B belongs_to a

The admin-user can generate new a-entries and he can generate new b-entries. The no-admin-user can show, index or reserve.

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

In the app/views/admin/as/show.html.erb you can see the values of the DB Entry of an a. So now my idea is to realise that you can add new B Entries of b with a form. I tried this 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>

The form will be generated, but the html-sourcecode don't show the "admin-route-path". But how do i this?

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

How have i to change the form_with part, that i can add entries into the associated model from b?


回答1:


Seems you want your form to hit the url /admin/as/bs. To build links to a namespaced controller you can use this forms:

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

The same is applicable to forms

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

The name of the route helper might be wrong. Check rake routes's output.




回答2:


To get route that you are looking for you need to have nested resources. You can find a great explanation here.




回答3:


I found the solution for the associated model and it works fine. Can anyone confirm this. Thanks

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



来源:https://stackoverflow.com/questions/49366165/rails-how-to-use-associated-model-with-the-admin-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!