2010-12-14 143 views
0

我是Rails3的新手,我只是想在我稱它爲黑夜之前讓最後一件事情起作用。情況如下(如果代碼太差,請告訴我,還在學習):rails3 has_one關聯模型創建

我想登錄潛水。我可能在那個潛水點上有一個新的位置,在這個位置我必須創建一個新的位置,然後創建潛水。潛水有一個位置。一個位置has_many潛水。目前外鍵作爲location_id在潛水中。

我該如何在我的dives_controller中正確生成位置,獲取ID並將它傳遞給我的新潛水?有位置的構造函數調用會很好,但如果它不以那種方式工作,那也沒關係。

我的代碼如下:

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 

回答

0

其實,你的建模需要一些工作,你應該看看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