简体   繁体   中英

Rails, request to another controller

I have three models Client , Service , Favourite . Structure of Favourite is:

class Favourite
  include Mongoid::Document
  include Mongoid::Timestamps

  #Associations
  belongs_to :client
  belongs_to :service
end

Which means Clients and Services has many Favourites . I am creating dashboard for my models. In view where single Clients info is shown, I want to show its Favourites , same will be on view of single Services .

I want to add form to create Favourites , but this model will not have its own views. It will be shown through Clients and Services .

My first idea is to create two different methods for controllers of Clients and Services .

My second idea is to create separate controller for Favourites that will create this model then redirect to clients and services.

Is it possible to call controller that is not connected with view?

Yes, you can have a controller without views.

Several options exist:

  • Use nested forms and cocoon to generate the related data within the parent forms. No controller is necessary for the favorites.

  • Use a form in the parent views that send to a favorites controller, which redirects back to the parent view. It just redirects somewhere else with redirect_to

    • to use the same controller method but redirect to different parent pages, include a hidden form element return_to which can be used to determine where to redirect. Filter the value though to be sure it's an allowed url, otherwise you might have a security hole.
  • Similar to the last option, but use javascript/ajax to send and receive the data. Again the controller may not have a view, but sends JSON or XML or whatever.

I think you should use polymorphic associations. In Favourite you should store favouritable_id and favouritable_type . { favouritable_id: "a", favouritable_type: "Client" } will mean that Favourite is connected with client id "a". To FavouriteController#create you need to pass params id and type of client/service . In view . In view render collection: client.favourites or render collection: service.favourites . I am not sure if . I am not sure if Mongoid classes implement to_partial_path` method, you can do it yourself it is easy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM