繁体   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