私はモデルの投稿を持っています:
class Post < ActiveRecord::Base
has_one :location, :dependent => :destroy
belongs_to :person
belongs_to :activity
私はモデルの場所を持っています:
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?
指定された場所から50マイル以内にあるすべての投稿を検索する必要があります。例を探しましたが、必要なものが見つかりませんでした。私は2つの方法で問題を解決しようとしましたが、失敗しました。私はRailsの初心者であり、問題に数えられていません。has_oneモデルを使用している他の人にも役立つと思います。
私は試した:
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>
エラーが発生しました:
PostsController#indexのNoMethodError予期していなかったときにnilオブジェクトがあります。配列のインスタンスを期待していたかもしれません。nilの評価中にエラーが発生しました。<<
何が悪いのか助けてください。たぶん、これには他の簡単な方法があります。
また、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
この場合、SQLに問題がありました。