I have the model Post:
class Post < ActiveRecord::Base
has_one :location, :dependent => :destroy
belongs_to :person
belongs_to :activity
I have the model Locations:
class Location < ActiveRecord::Base
belongs_to :post
validates :address, :presence => true
attr_accessible :address, :latitude, :longitude
geocoded_by :address
after_validation :geocode, :if => :address_changed?
I need to find all Posts which are in 50 miles from given location. I looked for examples but a did not find what I need. I tried to solve the problem in two ways and failed. I am beginner in Rails and uncounted with the problem, I think that It will be useful for other using has_one model.
I tried:
posts_controller.rb
def index
if params[:saddress].present?
@locations = Location.near(params[:saddress], 50, :order => :distance)
for location in @locations
@posts << location.post
end
else
@posts = Post.all
end
index.html.erb
<h1>Events</h1>
<fieldset>
<legend>Find event</legend>
<%= form_tag(posts_path, :method => "get") do %>
<%= label_tag(:saddress, "Address:") %>
<%= text_field_tag :saddress, params[:saddress] %> <br/>
<%= label_tag(:sactivity, "Activity type:") %>
<%= select_tag :sactivity, options_from_collection_for_select(Activity.all, "id", "name", params[:sactivity]) %>
<%= submit_tag "Поиск"%>
<%end%>
</fieldset>
<%if @user%>
<%= link_to "Новое событие", new_post_path %>
<%end%>
<table>
<tr>
<th>Created</th>
<th>Author</th>
<th>Event</th>
<th>Address</th>
<th>Activity type</th>
</tr>
<% for post in @posts.sort.each %>
<%if post%>
<tr>
<td><%= post.created_at %></td>
<td><%= post.person.name %></td>
<td><%= link_to post.name, post %></td>
<td><%if post.location%><%= post.location.address %> <%end%></td>
<td><%= post.activity.name %></td>
</tr>
<%end%>
<%end%>
</table>
It resulted in error:
NoMethodError in PostsController#index
You have a nil object when you didn’t expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.<<
Please help me what is wrong. Maybe there is some other easy method for this.
Also I tried this one in posts_controller.rb:
if params[:saddress].present?
@locations = Location.near(params[:saddress], 50, :order => :distance)
@posts = Post.find(:all, :include => [:location], :conditions => ["locations.id in ?", @locations])
else
@posts = Post.all
end
In this case I had problem with SQL.
In your
PostsController#indexmethod, you need to initialize the@postsvariable. to be an array before you can append items to it. If you ommit that (like you did), @posts is going to be implicitly initialized tonilwhich explains your error. Change your code like this:Another (shorter) variant of the above code is