0

我有一个 Location 模型和一个 Answer 模型,我正在尝试加入这两者,以便在创建 Answer 时,它与 Location 相关联。我添加了适当的 has_one 和 belongs_to 关联,添加了迁移以将 Locations id 添加到 Answer 表。

问题是当一个答案被创建时,'location_id' 为 nil。

任何帮助将不胜感激。这是我的文件:

位置模型

class Location < ActiveRecord::Base
  require 'Geoip-rails'
  has_one :answer

  def self.get_location
geoip = GeoIP.new("lib/GeoLiteCity.dat")
    l = Location.new
    l.city = geoip.country('78.151.144.93').city_name
    l.save
  end 
end

答案模型

class Answer < ActiveRecord::Base
  belongs_to :location
  belongs_to :question
  belongs_to :choice
  has_one :question, :through => :choice
end

将位置添加到 Answers 迁移

class AddLocationToAnswers < ActiveRecord::Migration
  def change
    add_column :answers, :location_id, :integer
    add_index :answers, :location_id
  end
end

问题控制器 - 回答操作

def answer
  @choice = Choice.find(params[:id])
  @location = Location.get_location
  @answer = Answer.create(:question_id => @choice.question_id, :choice_id => @choice.id)
  redirect_to questions_url
end

更新:

我现在已经从米沙的评论中改变了协会。

现在在控制台中我可以这样做并加入模型:

1.9.3-p392 :013 > a = Answer.last
Answer Load (0.2ms)  SELECT "answers".* FROM "answers" ORDER BY "answers"."id" DESC LIMIT 1
=> #<Answer id: 13, question_id: 1, choice_id: 2, created_at: "2013-07-05 09:50:28", updated_at: "2013-07-05 09:50:28", location_id: nil> 
1.9.3-p392 :014 > a.location
 => nil 
1.9.3-p392 :015 > a.location = Location.last
Location Load (0.2ms)  SELECT "locations".* FROM "locations" ORDER BY "locations"."id" DESC LIMIT 1
 => #<Location id: 25, lat: nil, lon: nil, city: "London", created_at: "2013-07-05 09:50:28", updated_at: "2013-07-05 09:50:28"> 
1.9.3-p392 :016 > a
 => #<Answer id: 13, question_id: 1, choice_id: 2, created_at: "2013-07-05 09:50:28", updated_at: "2013-07-05 09:50:28", location_id: 25> 
1.9.3-p392 :017 > 

我已经尝试在控制器中的“回答”操作中实现这一点,如下所示:

@answer = Answer.create(:question_id => @choice.question_id, :choice_id => @choice.id, :location_id => @location.id)

但是 :location_id => @location.id 给我一个错误:

未定义的方法“id”为真:TrueClass

我不知道如何在控制器中组合这两个模型

解决了

对于任何有兴趣的人。我的 get_location 方法没有做它应该做的事情。我必须在保存对象 l 后调用它。5 小时的头部撞击,所需要的只是“l”。

def self.get_location
geoip = GeoIP.new("lib/GeoLiteCity.dat")
 l = Location.new
 l.city = geoip.country('78.151.144.93').city_name
 l.save!
 l
end 
4

0 回答 0