简体   繁体   中英

foreign key in ruby on rails application

I have three models in a Ruby on Rails application:

  1. Magazine
  2. Product
  3. Page

I want to use this query:

Magazine.find(1).products.first.pages

and get a page associated with appropriate product but in page model I don't want product_id be my foreign key I want number_id be my foreign key. number is a field in product table. how can change foreign key? because rails work with product_id as foreign key for page table. tnx for your help.

The API documentation has all the answers. See the options for #has_many . You probably want to specify the relationship this way:

class Page < ActiveRecord::Base
  belongs_to :product, foreign_key: "number_id"
end

class Product < ActiveRecord::Base
  has_many :pages
end

It's not totally clear to me from your question, but if the primary key for your product table isn't :id then you'll need to also specify primary_key: "number" or whatever your primary key is.

I will write the appropriate codes for your models.

class Magazine < ActiveRecord::Base
  has_many :products
  has_many :pages, :through => :products
end


class Product < ActiveRecord::Base
  set_primary_key "number"
  belongs_to :magazine
  has_many :pages, foreign_key: "product_number"

  def my_pages
    self.pages.find_all { |p| p.magazine_id == self.magazine_id}
  end  
end

class Page < ActiveRecord::Base
end

You can call Magazine.first.products.first.my_pages

and it will return correct results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM