开发者

ActiveRecord in helper

This is my first time using a rails helper, and haven't found much documentation on how to output an activerecord search in a helper.

What I have is a tasks form, and a task can have a location. I don't want users entering locations, but instead have a text-box with autofill where the user can search for a location. When the user selects a location, I populate a hidden 'location_id' field with the location_id.

I'm using jQuery jsonSearch for the autofill, so I have to output all the location table fields into a javascript object when the page loads.

I figured my helper would just be something like

module TaskHelper

  def location_search
    @location = Location.search("location_id, address")
    @location.include_root_in_jason=false
  end

end

and then in my _form.html.erb I have

var locations=<%= raw location_search.to_json %>;

Is this the wrong way to be using helpers? I also tried without the @location but I just keep getting var locations = false;

I thou开发者_运维问答ght it best not to put the query into the tasks_controller because when I did that, all of the locations where showing up as part of the tasks/edit & tasks/new objects, and I figured that was bad.


Methods return the last expression in Ruby.

So to have a method that returns your list of locations, ensure that the last expressions returns the list. Simply putting @location by itself on the last line should do it. Then it'd work with a local variable.

However you should probably put the collection into an instance var in your controller and use that instead of using Active Record from in a helper. Putting model code in helpers can make it hard to find and its generally considered the controllers job to use model code.

Just say @location_json = Location.search("location_id, address") in your controller, then you can use the @location_json var in your template.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜