开发者

link to a controller function from the view

开发者 https://www.devze.com 2023-01-14 09:27 出处:网络
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.

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')
      De开发者_开发技巧commission.update(id, :username => username)
    else

    end
end


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%>
    


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

0

精彩评论

暂无评论...
验证码 换一张
取 消