簡體   English   中英

命名空間路線和模型路徑軌道

[英]Namespaces route and model path rails

我剛開始使用Rails,直到現在我對它感到非常滿意,但是有一件事我不知道。

我在名稱空間“監視器”中有一些ActiveRecords模型,在名稱空間“設置”中有一些控制器。 我要完成的工作是可以在我的設置控制器/窗體中使用命名空間模型。

我有這個:

/config/routes.rb

namespace :settings do
  resources :queues, :channels
end

/app/controllers/settings/queus_controller.rb

class Settings::QueuesController < ApplicationController

  def new
    @queue = Monitor::Queue.new()
    render 'form', :layout => false
  end

  def create
    @queue = Monitor::Queue.new(post_params)

    if (@queue.save)
      @status = 'added'
      render 'success'
    else
      render 'form', :layout => false
    end
  end

  def edit
    @queue = Monitor::Queue.find(params[:id])
    render 'form', :layout => false
  end

  ...
end

/app/models/monitor/queue.rb

module Monitor
  class Queue < ActiveRecord::Base
  end
end

/app/views/settings/form.html.erb

<%= form_for @queue do |f| %>
  ...
<% end %>

現在,Rails抱怨缺少一種方法: monitor_queues_path或Rails生成類似/monitor/queues的路徑,而不是/settings/queues(:new/edit)

我在這里想念什么?

我找到了!

這篇文章給了我適當的解決方案: 沒有模塊前綴路由路徑的Rails namescoped模型對象

問題來自ActiveRecord類的前綴:

module Monitor
  class Queue < ActiveRecord::Base
  end
end

這應該是

module Monitor
  class Queue < ActiveRecord::Base
    def self.model_name
      ActiveModel::Name.new("Monitor::Queue", nil, "Queue")
    end
  end
end

更改之后,我只需要以正確的方式更改form_for:

<%= form_for [:settings, @queue] do |f| %>

並修復它:D

您正在為Queue模型使用嵌套。 因此,您的form_for調用也需要了解父模型。 因此,在您的情況下,您將“ Queue ”嵌套在“ Setting下,因此您還需要提供一個setting對象。 我猜在你的控制器你做了一個@setting變量。 在這種情況下,以下代碼將為您工作。

<%= form_for [@setting, @queue] do |f| %>
    <%# Your form code here -%>
<% end -%>

我從我的朋友@mkhairi找到了一個解決方案,他說要在父模型上使用它:

class YourParentModel < ApplicationRecord
      def self.use_relative_model_naming?
        true
      end
end

那么您可以使用您的可愛短路。

來源: https : //coderwall.com/p/heed_q/rails-routing-and-namespaced-models

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM