views:

31

answers:

2

I have a function to take ownership of a job which updates the database to update the username in a table row. I want to link to this function from the view and then redirect to the appropriate page.

How do you link to a controller function or a model function from the view?

from the index i want to have another link beside show, edit, delete, which says 'take ownership' This will then fire off an action in the application controller

def accept_job(job_type, id, username)
    if (job_type == 'decom')
      Decommission.update(id, :username => username)
    else

    end
end
A: 

You can use the instance variable @controller to get a reference to the controller. As for calling a model function, you can call Model.function to call class methods, or if you have a particular Model instance called model_instance, then use model_instance.function to call an instance method.

Edit: Okay, I think I understand what you're asking now.

You should

  1. Create a new action in the controller, let's call it update_username:

    def update_username job = Job.find(params[:id]) job.your_method #call your method on the model to update the username redirect_to :back #or whatever you'd like it to redirect to end

  2. Add your action the routes in routes.rb. See Rails Routing from the Outside In for more details.

  3. Add your link in the view:

    <%=link_to "Update my username please!", update_username_job_path%>

unsorted
So its ok to add lots of custom actions in the controllers?
inKit
What if the action is in the application controller?
inKit
If by "custom actions" you mean "stuff other than the default REST actions created by scaffolding" then...definitely yes. Controllers are for making your model and view communicate with each other, which clearly has to happen here. You should be probably putting it in the JobController rather than the ApplicationController, though.
unsorted
A: 

Hi user424677

First you create a function in your model, say

class Decommission

def assign_permission(name) #your update code end

end

As I can see, you can do this in 3 different ways

1 - Create a helper method to update the permission (This can be done either in Application helper or helper related to your view)

2 - By creating a controller method (as you proposed) But if you are not using this method in other views you dont need to create this method in application controller

3 - If you want to use your method in both controllers and views, create your method in application controller and make it as helper method. By that way you can access it from controllers as well as views

cheers

sameera

sameera207