Searching through association with Geocoder on Rails, Cannot visit ActiveRecord::Relation::ActiveRecord_Relation error

StackOverflow https://stackoverflow.com//questions/24005691

Question

I have a Posts resource which belongs to a Poster(a user type) whose address is geocoded using the Geocoder gem successfully upon registration. Now I want a user to able to search for posts near them by distance. I am relatively new to Rails, any help would be greatly appreciated.

I get the following error (I don't really know what it means, I thought setting up associations in my models was enough)

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

Posts model

class Post < ActiveRecord::Base
belongs_to :poster
end

Poster model

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

User Model

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
Was it helpful?

Solution

I just ended up passing the attributes on the creation of the post, I wish there were a way to solve my original problem (makes the database less redundant)

in my Post Controller

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

Also used "geocoded by :poster" in my Posts model

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top