Where is the controller of Devise ? how to add data from other models in users/edit page?

自闭症网瘾萝莉.ら 提交于 2020-01-05 02:05:05

问题


it seems devise do not create any controller file in app/controller folder, now I am looking to show some custom info from other models in users/edit view but not able to figure out how to do it since there is no controller to add

@num_of_cars = current_user.num_of_cars.all

I am looking to show num_of_cars in users/edit page but not able to figure out how to do it

EDIT - the below mentioned code giving me error, I am putting this code in my devise/registration/edit file

<%= render partial: 'myinfo/cars_list' %> 

where myinfo is another resource with a partial _cars_list.html.erb, the /myinfo scaffold works perfectly fine but when I am trying to display that partial into users/edit, it is giving me

undefined method `each_with_index' for nil:NilClass  

(I am using each_wit_index to display list but I don't think that is the problem)


回答1:


Override the Devise sessions controller actions:

# app/controllers/sessions_controller.rb
class SessionsController < Devise::SessionsController

  def edit
    # add custom logic here
    @num_of_cars = current_user.num_of_cars.all 
    super
  end

end 

Register the controller:

# app/config/routes.rb
devise_for :users, :controllers => {:sessions => "sessions"}



回答2:


You can create new controller for handel devise/registration/edit

here's is controller/passwords_controller.rb

class PasswordsController < Devise::RegistrationsController
  before_filter :authenticate_user!
  def edit
    @num_of_cars = current_user.num_of_cars.all
    super
  end

  def update
    @user = current_user
    # raise params.inspect
    if @user.update_with_password(params[:user])
      sign_in(@user, :bypass => true)
      redirect_to user_path, :notice => "Password has been change!"
    else
      render :edit,:locals => { :resource => @user, :resource_name => "user" }
    end
  end
end

here's is routes.rb

devise_scope :user do
 get '/edit_password' => 'passwords#edit', :as => :change_password
 put '/change' =>  'passwords#update'
end

and finaly you can copy devise/registrations/edit.html.erb to passwords/edit.html.erb




回答3:


In your case, you dont have to override the devise controller. You can replace

<%= render partial: 'myinfo/cars_list' %> 

with

<%= render partial: 'myinfo/cars_list', :locals => { :num_of_cars => current_user.num_of_cars.all } %>

in your devise/registration/edit page. Then using "num_of_cars" variable instead of "@num_of_cars", inside your 'myinfo/cars_list' partial, should fix your issue.



来源:https://stackoverflow.com/questions/15965127/where-is-the-controller-of-devise-how-to-add-data-from-other-models-in-users-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!