rails3 has_one association model creation
I'm new to Rails3, and I'm just trying to get one last thing to work before I call it a night. The situation is the following (please if the code is horrible, just let me know, still learning):
I want to log a dive. I might have a new location on that dive at which point I have to create a new Location, and then create the dive. A dive has_one location. A location has_many dives. Currently the foreign key is on dive as location_id.
How do I properly, in my dives_controller, generate the location, get the ID, and pass it on to my new dive? It would be nice to have the constructor of Location called, but if it doesn't work that way, then that's okay too.
My code is below:
class Dive < ActiveRecord::Base
belongs_to :user
has_one :location
end
require 'json'
require 'net/http'
require 'uri'
class Location < ActiveRecord::Base
has_many :dive
def initialize(location)
@name = location[:name]
@city = location[:city]
@region = location[:region]
@country = location[:country]
url = "http://maps.googleapis.com/maps/api/geocode/json?address="+location[:city].sub(' ', '+')+"+"+location[:region].sub(' ', '+')+"+"+location[:country].sub(' ', '+')+"&sensor=false"
resp = Net::HTTP.get_response(URI.parse(url))
googMapsResponse = JSON.parse(resp.body)
@latitude =开发者_运维问答 googMapsResponse["results"][0]["geometry"]["location"]["lat"]
@longitude = googMapsResponse["results"][0]["geometry"]["location"]["lng"]
end
def to_str
"#{self.name}::#{self.city}::#{self.region}::#{self.country}"
end
end
class DivesController < ApplicationController
def create
@dive = Dive.new(params[:dive])
if params[:location][:id] == "" then
@location = create_location(params[:location])
@dive.location_id = @location.id
else
@dive.location_id = params[:location][:id]
end
@dive.user_id = params[:user][:id]
end
end
Actually, your modelling needs some work and you should look at nested_attributes.
class Dive < ActiveRecord::Base
belongs_to :user
has_one :location
end
class Location < ActiveRecord::Base
has_many :dives
def to_str
...
end
end
class DivesController < ApplicationController
def create
@dive = Dive.new(params[:dive])
if params[:location][:id] == "" then
# Create new Location
@location = Location.new(params[:location])
url = "http://maps.googleapis.com/maps/api/geocode/json?address=" +
@location[:city].sub(' ', '+') + "+" +
@location[:region].sub(' ', '+') + "+" +
@location[:country].sub(' ', '+') + "&sensor=false"
resp = Net::HTTP.get_response(URI.parse(url))
googMapsResponse = JSON.parse(resp.body)
@location.latitude = googMapsResponse["results"][0]["geometry"]["location"]["lat"]
@location.longitude = googMapsResponse["results"][0]["geometry"]["location"]["lng"]
@location.save
@dive.location = @location
else
@dive.location_id = params[:location][:id]
end
# This can be improved
@dive.user_id = params[:user][:id]
if @dive.save
# do something
else
# do something else
end
end
end
精彩评论