Location モデルと Answer モデルがあり、2 つを結合しようとしているので、Answer が作成されると Location に関連付けられます。適切な has_one および belongs_to 関連付けを追加し、ロケーション 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 は私にエラーを与えます:
true:TrueClass の未定義のメソッド「id」
コントローラーで 2 つのモデルを組み合わせる方法がわかりません
解決済み
興味のある方へ。私の 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