Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

ruby on rails - How to create controllers in different namespace for an existing model?

I have a Product model in my rails app. Now I want to create a controller and views for this product model through scaffolding in a different namespace(api).

Till now I have tried using

rails g scaffold_controller product name:string price:integer 

and after this I added the this to my routes file

namespace :api do
  resources :products
end

Now when I go to the link api/products . I get this error

uninitialized constant Api::Product

on the index action

def index
   @api_products = Api::Product.all
end

After this I removed the Api:: from my controller index, new and create action. After doing this my index url (/api/products) was working fine but now when I try to create a new product(/api/products/new) I get the following error

undefined method `products_path' 

This is the code for my model file (location is models/)

class Product < ActiveRecord::Base
end

Can anyone please help in implementing this correctly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should move product.rb to app/models/api and change the class name to Api::Product

#app/models/api/product.rb
class Api::Product < ActiveRecord::Base
  self.table_name = "products"
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...