I am using geocoder gem and gmaps4rails gem. I have followed the instructions for installing both, and I am able to display a dummy map on my page, however, when I try to add in the #hash from my controller, the markers do not show. Any help would be appreciated! I am a newbie :-)
My 'Show' view:
<script type="text/javascript">
handler = Gmaps.build('Google');
handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
markers = handler.addMarkers(<%=raw #hash.to_json %>);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
});
</script>
My Trail Controller:
def index
#trails = Trail.all
#hash = Gmaps4rails.build_markers(#trails) do |trail, marker|
marker.lat trail.latitude
marker.lng trail.longitude
marker.title trail.title
end
end
def show
#trail = Trail.find(params[:id])
#posts = #trail.posts
#hash = Gmaps4rails.build_markers(#trails) do |trail, marker|
marker.lat trail.latitude
marker.lng trail.longitude
marker.title trail.title
end
end
def new
#trail = Trail.new
end
def create
#trail = Trail.new(params.require(:trail).permit(:title, :state, :address, :latitude, :longitude, :body, :images))
if #trail.save
flash[:notice] = "Trail was saved."
redirect_to #trail
else
flash[:error] = "There was an error saving the trail. Please try again."
render :new
end
end
My Trail Model:
class Trail < ActiveRecord::Base
belongs_to :user
has_many :posts
mount_uploader :images, ImagesUploader
geocoded_by :address
after_validation :geocode
end
Related
I use gem 'nested_form' in rails 3.2
Models:
meeting_agenda.rb:
class MeetingAgenda < ActiveRecord::Base
has_many :meeting_questions, :inverse_of => :meeting_agenda
accepts_nested_attributes_for :meeting_questions, allow_destroy: true
attr_accessible :meeting_questions_attributes
end
meeting_question.rb:
class MeetingQuestion < ActiveRecord::Base
has_one :meeting_answer, :inverse_of => :meeting_question
accepts_nested_attributes_for :meeting_answer
attr_accessible :meeting_answer_attributes
end
meeting_answer.rb
class MeetingAnswer < ActiveRecord::Base
belongs_to :meeting_question
end
Controller:
class MeetingProtocolsController < ApplicationController
def new
#agenda = MeetingAgenda.new
rescue => error
render_403
end
def create
#agenda = MeetingAgenda.new(params[:meeting_agenda])
if #agenda.save && protocol.save
flash[:notice] = l(:notice_successful_create)
redirect_to action: 'show', id: #agenda.id
else
render action: 'new'
end
end
View:
new.html.haml:
= nested_form_for #agenda do |f|
# ...
= f.fields_for :meeting_questions do |question|
# ...
# Fields for answer is not showing!
= question.fields_for :meeting_answer do |answer| # <-- blank
%p # <-- blank
= answer.label :reporter_id_is_contact, t(:label_meeting_question_user_is_contact) # <-- blank
= answer.check_box :reporter_id_is_contact; # <-- blank
= question.link_to_remove l(:button_delete) # <-- blank
= f.link_to_add l(:button_add), :meeting_questions
= submit_tag l(:button_create)
has_one relation with accepts_nested_attributes_for is empty.
Same form working great on rails 5.
Maybe it's a case of the Mondays but I'm having a really difficult time with infowindows and the Google Maps for Rails gem. Does anyone know of a tutorial or example?
All I want to do is set up a default infowindow to open when you click on a marker. I've gathered that I need to make a partial and set the options in the map but I just can't seem to bring it all together.
Thanks!
Nevermind, it finally clicked. Here's my code for a basic example, hopefully it will help someone else in the future.
location model
class Location < ActiveRecord::Base
include Rails.application.routes.url_helpers
default_scope order('locations.id ASC')
acts_as_gmappable
attr_accessible :name,
:address,
:city,
:province,
:postal_code,
:country,
:phone,
:ext,
:phone_alt,
:ext_alt,
:latitude,
:longitude
geocoded_by :address
validates_presence_of :name
validates_presence_of :address
validates_presence_of :city
validates_presence_of :province
validates_presence_of :postal_code
validates_presence_of :country
after_validation :geocode, :if => :address_changed?
def gmaps4rails_address
#describe how to retrieve the address from your model, if you use directly a db column, you can dry your code, see wiki
"#{self.address}, #{self.city}, #{self.country}"
end
end
location controller
class LocationsController < ApplicationController
def show
#location = Location.find(params[:id])
#json = #location.to_gmaps4rails do |location, marker|
marker.infowindow render_to_string(:partial => "/layouts/partials/infowindow", :locals => { :location => location})
end
respond_to do |format|
format.html
end
end
end
infowindow partial (haml)
.location-data{id: location.id}
.location-name
= location.name.capitalize
.location-address
= location.address.capitalize
.location-city= location.city.capitalize
.location-province
= location.province.capitalize
.location-postal-code
= location.postal_code
.location-country
= location.country
.location-phone
= location.phone
.location-extension
= location.ext
.location-alt-phone
= location.phone_alt
.location-alt-phone-extension
= location.ext_alt
show view (haml)
#map-column
%h1
Find a retailer near you
= gmaps("markers" => {"data" => #json, "options" => {"link_container" => "map_link_" } })
I'm just following Ruby on Rails 3 Tutorials (Mhartl) chapter-7 at the stage of 7.3.2 name and Gravatar.
Here I am facing a problem when I open on my browser it's says:
ActiveRecord::RecordNotFound in UsersController#show
Couldn't find User with id=1
Rails.root: C:/RubyOnRails/MyWorkPlace/sample_app_1
Application Trace | Framework Trace | Full Trace
app/controllers/users_controller.rb:5:in `show'
Request
Parameters:
{"id"=>"1"}
Show session dump
Show env dump
Response
Headers:
None
Also I pasted below User_controller.rb and user.rb
user.rb:
require 'digest'
class User < ActiveRecord::Base
attr_accessor :pasword
attr_accessible :login,
:username,
:email,
:password,
:password_confirmation,
:remember_me
email_regex = /\A[\w+\-.]+#[a-z\-.]+\.[a-z]+\z/i
validates :name, :presence => true,
:length => { :maximum => 50 }
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
validates :pasword, :presence => true,
:confirmation => true,
:length => { :within => 6..40 }
def self.authenticate(email, submitted_password)
user = find_by_email(email)
return nil if user.nil?
return user if user.has_password?(submitted_password)
end
before_save :encrypt_password
def has_password?(submitted_password)
encrypted_password == encrypt(submitted_password)
end
private
def encrypt_password
self.salt = make_salt if new_record?
self.encrypted_password = encrypt(password)
end
def encrypt(string)
secure_hash("#{salt}--#{string}")
end
def make_salt
secure_hash("#{Time.now.utc}--#{password}")
end
def secure_hash(string)
Digest::SHA2.hexdigest(string)
end
end
users_controller.rb:
class UsersController < ApplicationController
def show
#user = User.find(params[:id])
#title = #user.name
end
def new
#title = "Sign up"
end
end
Are you sure you created any user with id=1 ?
To check, go to rails console and get the user with id 1. If there is no user, then create one.
At firest, I see you have attr_accessor :pasword
I think it should be :password
Ontopic:
There are some actions missing in the restful controller, so it wont be possible to create a user.
See http://guides.rubyonrails.org/getting_started.html#rest for more details on RESTful controllers.
class UsersController < ApplicationController
def show
#user = User.find(params[:id])
#title = #user.name
end
def new
#user = User.new #this creates a empty user object to be filled with signup data
#title = "Sign up"
end
def create
#user = User.new(params[:user]) #this creates a new user object with the data you entered before.
if #user.save #if the data is valid, save it
redirect_to user_path(#user) #and go to the #user show action
else
render :action => :new #edit the invalid user data
end
end
def edit
#user = User.find(params[:id])
end
def update
#user = User.find(params[:id])
if #user.update_attributes(params[:user])
redirect_to user_url(#user)
else
render edit_user_url(#user)
end
end
def index
#users = User.all
end
def destroy
#user = User.find(params[:id]
#user.destroy
redirect_to :action => :index
end
end
edit: complete restful actions
I had the same problema. In my case, my 'redirect_to' on my detroy action was missin a 's' in 'posts_path'. It was post_path Noob, but worth i had checked up.
The reason you could not find the "user/1" is when you Added microposts to the sample data(db/seeds.rb) by typing
users = User.order(:created_at).take(6)
50.times do
content = Faker::Lorem.sentence(5)
users.each { |user| user.microposts.create!(content: content) }
end
You forgot the "END" of the previous code, so the full picture of db/seeds.rb is
User.create!(name: "Example User",
email: "example#railstutorial.org",
password: "foobar",
password_confirmation: "foobar",
admin: true,
activated: true,
activated_at: Time.zone.now)
99.times do |n|
name = Faker::Name.name
email = "example-#{n+1}#railstutorial.org"
password = "password"
User.create!(name: name,
email: email,
password: password,
password_confirmation: password,
activated: true,
activated_at: Time.zone.now)
end
users = User.order(:created_at).take(6)
50.times do
content = Faker::Lorem.sentence(5)
users.each { |user| user.microposts.create!(content: content) }
end
I am trying to roll together two Railscasts: http://railscasts.com/episodes/262-trees-with-ancestry and http://railscasts.com/episodes/154-polymorphic-association on my app.
My Models:
class Location < ActiveRecord::Base
has_many :comments, :as => :commentable, :dependent => :destroy
end
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
My Controllers:
class LocationsController < ApplicationController
def show
#location = Location.find(params[:id])
#comments = #location.comments.arrange(:order => :created_at)
respond_to do |format|
format.html # show.html.erb
format.json { render json: #location }
end
end
end
class CommentsController < InheritedResources::Base
def index
#commentable = find_commentable
#comments = #commentable.comments.where(:company_id => session[:company_id])
end
def create
#commentable = find_commentable
#comment = #commentable.comments.build(params[:comment])
#comment.user_id = session[:user_id]
#comment.company_id = session[:company_id]
if #comment.save
flash[:notice] = "Successfully created comment."
redirect_to :id => nil
else
render :action => 'new'
end
end
private
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
end
In my locations show view I have this code:
<%= render #comments %>
<%= render "comments/form" %>
Which outputs properly. I have a _comment.html.erb file that renders each comment etc. and a _form.html.erb file that creates the form for a new comment.
The problem I have is that when I try <%= nested_comments #comments %> I get undefined method 'arrange'.
I did some Googling and the common solution to this was to add subtree before the arrange but that throws and undefined error also. I am guessing the polymorphic association is the problem here but I am at a loss as to how to fix it.
Dumb mistake... forgot to add the ancestry gem and required migration which I thought I had already done. The last place I checked was my model where I eventually discovered my error.
I'm trying to setup a photo gallery for each user. How would I set up the associations?
class User < ActiveRecord::Base
has_many :photos
has_many :galleries, through :photos
end
class Gallery < ActiveRecord::Base
has_many :photos
belongs_to :user
end
class Photo < ActiveRecord::Base
belongs_to :gallery
belongs_to :user
end
i have the gallery and photo model currently working. You are able to create a gallery and add photos to it. I'm confused is to how to add it to the current user?
class GalleriesController < ApplicationController
def index
#galleries = Gallery.all
end
def show
#gallery = Gallery.find(params[:id])
end
def new
#gallery = Gallery.new
end
def create
#gallery = Gallery.new(params[:gallery])
if #gallery.save
flash[:notice] = "Successfully created gallery."
redirect_to #gallery
else
render :action => 'new'
end
end
def edit
#gallery = Gallery.find(params[:id])
end
def update
#gallery = Gallery.find(params[:id])
if #gallery.update_attributes(params[:gallery])
flash[:notice] = "Successfully updated gallery."
redirect_to gallery_url
else
render :action => 'edit'
end
end
def destroy
#gallery = Gallery.find(params[:id])
#gallery.destroy
flash[:notice] = "Successfully destroyed gallery."
redirect_to galleries_url
end
end
PhotosController
class PhotosController < ApplicationController
def new
#photo = Photo.new(:gallery_id => params[:gallery_id])
end
def create
#photo = Photo.new(params[:photo])
if #photo.save
flash[:notice] = "Successfully created Photo."
redirect_to #photo.gallery
else
render :action => 'new'
end
end
def edit
#photo = Photo.find(params[:id])
end
def update
#photo = Photo.find(params[:id])
if #photo.update_attributes(params[:photo])
flash[:notice] = "Successfully updated Photo."
redirect_to #Photo.gallery
else
render :action => 'edit'
end
end
def destroy
#photo = Photo.find(params[:id])
#photo.destroy
flash[:notice] = "Successfully destroyed Photo."
redirect_to #photo.gallery
end
end
Once you grab the current user, just concatenate the gallery to the user's galleries.
def update
#gallery = Gallery.find(params[:id])
#user = current_user
if #gallery.update_attributes(params[:gallery])
#user.galleries << #gallery
flash[:notice] = "Successfully updated gallery."
redirect_to gallery_url
else
render :action => 'edit'
end
end