开发者

Ruby on Rails model associations nubie question

dear developers I have some problems with Rails models Here is my sql tables

  create_table "areas", :primary_key => "ndc", :force => true do |t|
    t.string "townname", :limit => 256, :null => false
  end

  create_table "books", :primary_key => "ndc", :force => true do |t|
    t.integer "booked", :null => false
    t.integer "free",   :null => false
  end



class Book < ActiveRecord::Base
  self.primary_key = "ndc"
  has_one :area, :foreign_key => 'ndc'
end

class Area < ActiveRecord::Base
    self.primary_key = "ndc"
    belongs_to :book , :foreign_key => 'ndc'
end

in co开发者_运维知识库ntroller I have such code

   @books = Book.paginate :page => params[:page] || 1, :per_page => 10
     @books.each do |booking|
      p booking.area
      p booking

     end

In production mode doesn't work, booking.area is nil object. what it can be ?

Area becames nil if config.cache_classes = true

so booking.area generates such queries if cashe_classes = true

SELECT areas.* FROM areas WHERE (areas.ndc = NULL) LIMIT 1 but without cashing classes SELECT areas.* FROM areas WHERE (areas.ndc = 30) LIMIT 1

FIXED by removing belongs_to :book , :foreign_key => 'ndc' from area class.


Your areas table needs a book_id integer field to match against the books table's primary key.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜