Cześć
Mam dwa modele: Channel i Broadcaster. Powiązane są w ten sposób, że channel należy do broadcaster a broadcaster has_many channels.
-
Z czystego SQL:
select id, broadcaster_id from channels;
id | broadcaster_id
-----±---------------
276 | 49 -
Konsola railsów:
irb(main):004:0> Channel.find(276)
Channel Load (0.4ms) SELECT “channels”.* FROM “channels” WHERE “channels”.“id” = $1 LIMIT 1 [[“id”, 276]]
=> #<Channel id: 276, broadcaster_id: 49, name: “TVP 1 HD”, report: true, term: “7,this month”, price: nil, email: “raporty@tvp.pl”, created_at: “2015-02-10 10:53:56”, updated_at: “2015-02-10 10:53:56”, currency: “PLN”>
irb(main):005:0> Channel.find(276).broadcaster_id
Channel Load (0.4ms) SELECT “channels”.* FROM “channels” WHERE “channels”.“id” = $1 LIMIT 1 [[“id”, 276]]
=> nil
irb(main):006:0> Channel.find(276).broadcaster.id
Channel Load (0.4ms) SELECT “channels”.* FROM “channels” WHERE “channels”.“id” = $1 LIMIT 1 [[“id”, 276]]
Broadcaster Load (0.2ms) SELECT “broadcasters”.* FROM “broadcasters” WHERE “broadcasters”.“id” = $1 LIMIT 1 [[“id”, 49]]
=> 49
Czemu Channel.find(276).broadcaster_id zwraca nil?
Dodam, że może to być problem z tym w jaki sposób nakarmiłem bazę. Zrobiłem to tak (seed.rb)
Broadcaster.create(name: ‘TVP’).channels.create([
[{:name=>“TVP 1 HD”, :report=>true, :term=>“7,this month”, :email=>“raporty@tvp.pl”, :currency=>“PLN”}],
[{:name=>“TVP 2 HD”, :report=>true, :term=>“7,this month”, :email=>“raporty@tvp.pl”, :currency=>“PLN”}],
itd.