rails3 has_one关联模型创建

时间:2010-12-14 09:17:42

标签: ruby-on-rails-3

我是Rails3的新手,我只想在我称之为晚上之前让最后一件事情起作用。情况如下(如果代码很糟糕,请告诉我,仍在学习):

我想记录潜水。我可能在该潜水中有一个新位置,此时我必须创建一个新位置,然后创建潜水。潜水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

1 个答案:

答案 0 :(得分: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