通过与Rails上的Geocoder关联搜索,无法访问ActiveRecord :: Relation :: ActiveRecord_Relation错误

时间:2014-06-03 01:15:40

标签: search ruby-on-rails-4 rails-activerecord rails-geocoder

我有一个属于海报(用户类型)的帖子资源,其地址在注册时使用Geocoder gem成功进行地理编码。现在我希望用户能够按距离搜索他们附近的帖子。我对Rails相对较新,任何帮助都将不胜感激。

我收到以下错误(我真的不知道这意味着什么,我认为在我的模型中设置关联就足够了)

Cannot visit ActiveRecord::Relation::ActiveRecord_Relation_Poster

index.html.erb

<%= form_tag posts_path, method: :get do %> 
Find postings <%= select_tag "within", options_for_select([["Next door", 0.001],["In your  neighborhood", 0.05], ["Nearby", 0.1]], ["Nearby", 0.1]) %>
<%= submit_tag "Find", :name => nil %>
<% end %>

posts_controller.erb

  def index
if params[:within]
  @posts= Post.where(Poster.near(current_user, params[:within].to_f))
else
 @posts=Post.all
 end
end

帖子模型

class Post < ActiveRecord::Base
belongs_to :poster
end

海报模型

class Poster < User
has_many :posts, dependent: :destroy   
end

用户模型

class User < ActiveRecord::Base
 def full_address
[address_one, city, state, zip].compact.join(', ')
 end 

geocoded_by :full_address, :latitude => :lat, :longitude => :long
after_validation :geocode, if: -> (full_address){ full_address.present? or     address_changed? }
end

1 个答案:

答案 0 :(得分:1)

我刚刚在帖子创建时传递了属性,我希望有一种方法可以解决我原来的问题(使数据库不那么冗余)

在我的帖子控制器中

def create
 @post = current_user.posts.build(post_params)
 @post.assign_attributes(:lat => current_user.lat, :long => current_user.long)
end

def index
if params[:within]
 @posts= Post.near(current_user, params[:within].to_f)
else
 @posts=Post.all
 end
end

也使用&#34;地理编码:海报&#34;在我的帖子模型中