2

In Rails4, I have an method named get_values_from_models in Controller which take an parameter id:

app/controller/bugs_controller.rb

def get_values_from_models(id)
  @online_bugs = Bugs.where(bug_id: id)
  @devlopers = Devs.where(dev_role_id: 2)
end

I would like to call this method within the Jquery functionshow_bug_detail, which is in an partial view:

app/view/bugs/_get_values.html.erb

var id =5;
function show_bug_detail(id) {
  //call method get_values_from_models, pass parameters 'id'
  //get @online_bugs and @developers instances from returned.
  }

Is that possible? How to do that? I have been searching the possible solutions for a while but without any fortune, it would be appreciate if someone can provide me any solution, thanks.

2
  • 1
    You need to use Ajax for this. Make a route to connect to the controller action you want to call. Then using Ajax call the controller action and return data from the action to the Jquery and use it. Commented Oct 24, 2015 at 16:04
  • You are correct, It turns out I should use Ajax to implement this. Commented Oct 25, 2015 at 5:31

1 Answer 1

3

Now note that for example purposes I've created the route as a collection. However, since this really is an action on the resource itself it would make more sense to create a member out of it. Perhaps you should look at that? This would create a route like /bugs/:id/get_values_from_models

I did not test the following code myself, but this is the basic idea.

Create a route for it, let's say:

(Also see the rails guides for reference: http://guides.rubyonrails.org/routing.html#resources-on-the-web)

resources :bugs do
  get get_values_from_models, on: :collection
end

I don't know when your function is triggered, but when it is you can put in the following code to fetch your results with an ajax get.

Also see the jQuery API for reference: http://api.jquery.com/jQuery.get/

$.get("bugs/get_values_from_models", {id: your_id}, function(data){
  // do something with your data received if everything went ok.
  // notice that you'll have to return json from your controller.
}, "json");

Make your method "get_values_from_models" accessible (so not private). Remove the id as a parameter. So something like this:

def get_values_from_models
  # when called you should receive a params[:id]
  id = params[:id]

  @online_bugs = Bugs.where(bug_id: id)
  @developers = Devs.where(dev_role_id: 2)

  # now return the results you'd like
  render json: {online_bugs: @online_bugs, developers: @developers}
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.