Reputation: 203
I'm just started with rails and until now I was very happy with it, but there is one thing I can't figure out.
I have some ActiveRecords models in a namespace "Monitor", and I have some controllers in a Namespace "Settings". What I want to accomplish is that I can use the namespaced models in my settings controllers/forms.
I've got this:
/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 %>
Now Rails is complaining about a missing method : monitor_queues_path
or Rails generates a path like /monitor/queues
instead of /settings/queues(:new/edit)
.
What am I missing here?
Upvotes: 1
Views: 1806
Reputation: 1972
I found a solution from my friend @mkhairi he said to use this on the parent model :
class YourParentModel < ApplicationRecord
def self.use_relative_model_naming?
true
end
end
then you can use back ur lovely short path.
Source : https://coderwall.com/p/heed_q/rails-routing-and-namespaced-models
Upvotes: 0
Reputation: 203
Aah I found it!
This post gave me the proper solution: Rails namescoped model object without module prefix route path
The problem came from the prefix from the ActiveRecord class:
module Monitor
class Queue < ActiveRecord::Base
end
end
This should be
module Monitor
class Queue < ActiveRecord::Base
def self.model_name
ActiveModel::Name.new("Monitor::Queue", nil, "Queue")
end
end
end
After changing this I only needed to change the form_for in the correct way:
<%= form_for [:settings, @queue] do |f| %>
And that fixes it :D
Upvotes: 6
Reputation: 3806
You are using nesting for your Queue
models. Therefore your form_for
call needs to know about the parent model too. So in your case you nested Queue
under Setting
so you will need to provide a setting
object as well. I'm guessing in your controller you made a @setting
variable. If this is the case then the following code will work for you.
<%= form_for [@setting, @queue] do |f| %>
<%# Your form code here -%>
<% end -%>
Upvotes: 1