2010-12-14 3 views
0

저는 Rails3을 처음 사용하기 때문에 밤에 호출하기 전에 마지막으로 한 가지 작업을하려고합니다. 상황은 다음과 같습니다. (코드가 끔찍한 경우 알려주세요. 배우고 아직 알려주세요.)rails3 has_one 연관 모델 생성

다이빙을 로그하고 싶습니다. 나는 그 다이빙에 새로운 위치를 가지고 새로운 위치를 만들어 다이빙을 만들어야합니다. 다이빙 has_one 위치. 위치 has_many 잠수. 현재 외래 키가 location_id로 다이빙 중입니다.

내 dives_controller에서 위치를 생성하고 ID를 얻은 다음이를 새 다이빙으로 전달하는 방법은 무엇입니까? Location 생성자를 호출하는 것이 좋을 것입니다. 그러나 그것이 그렇게 작동하지 않는다면, 역시 괜찮습니다.

내 코드는 다음과 같습니다 :

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