简体   繁体   中英

Rails call a controller user-defined method

I am working with rails I have a controller name books and has a user defined method in it .I need to call this method so that i can see the output on console.And I dont want to call this method in helpers.

def approve
    @user=current_user.users.find params[:id]
    puts '#{@usery}'     
  end 


Also I Have a link

<%= link_to 'approve',users_path,data: { :confirm => 'Are you sure to delete the folder and all of its contents?'} %>


.When i click on this link I want to call the above method on it .

You'll just need to define a route and call it through that:

#config/routes.rb
resources :users do
    get :approve, on: :member
end

<%= link_to "Approve", users_approve_path(@user) %>

As @Rich suggested that, you can achieve it by member . Please note that when you'll create a member route in member block

resources :users do
  member do
    get 'approve'
  end
end

then you'll get the params[:id] . Like

def approve
  @user = User.find params[:id]
  puts '#{@user}'     
end

and when create a member route using :on then you'll get params[:user_id] . Like

def approve
  @user = User.find params[:user_id]
  puts '#{@user}'     
end

Path will be same in both cases that is

<%= link_to "Approve", users_approve_path(@user) %>

Source Rails - Adding More RESTful Actions

Happy coding !!!

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