Rails 3:如何使用自定义 table 列作为 id 而不是常规 table id?
Rails 3: How can i use custom table column as id instead of the regular table id?
我有一个 table,由于特定原因,我必须使用自定义 table 列作为 ID:
table 表示有列 id,我想使用列 edavis_id 而不是 id。
#app/models/representation.rb:
class Representation < ActiveRecord::Base
attr_accessible :people_attributes, :name, :country_id, :rep_type_id, :address, :address_postal, :phone, :email, :fax, :homepage, :consular_district, :botschaftsfunk, :ivs, :ivpn, :idirect
belongs_to :country
belongs_to :rep_type
has_many :people
has_many :representation_telephones, foreign_key: :representation_id
accepts_nested_attributes_for :people
validates_uniqueness_of :remedy_site_id, allow_nil: true
has_many :device_representation_relations
has_many :devices, :through => :device_representation_relations
delegate :name_de, to: :rep_type, prefix: true, allow_nil: true
delegate :iso_code, to: :country, prefix: true, allow_nil: true
# omitted...
end
如何告诉 rails 使用 edavis_id 作为 ID(而不是常规的 table ID)?
只需添加:
class Representation < ActiveRecord::Base
self.primary_id = :edavis_id
#...
end
尝试:
class Representation < ActiveRecord::Base
self.primary_key = :edavis_id
#
end
http://ruby-journal.com/how-to-override-default-primary-key-id-in-rails/
我有一个 table,由于特定原因,我必须使用自定义 table 列作为 ID:
table 表示有列 id,我想使用列 edavis_id 而不是 id。
#app/models/representation.rb:
class Representation < ActiveRecord::Base
attr_accessible :people_attributes, :name, :country_id, :rep_type_id, :address, :address_postal, :phone, :email, :fax, :homepage, :consular_district, :botschaftsfunk, :ivs, :ivpn, :idirect
belongs_to :country
belongs_to :rep_type
has_many :people
has_many :representation_telephones, foreign_key: :representation_id
accepts_nested_attributes_for :people
validates_uniqueness_of :remedy_site_id, allow_nil: true
has_many :device_representation_relations
has_many :devices, :through => :device_representation_relations
delegate :name_de, to: :rep_type, prefix: true, allow_nil: true
delegate :iso_code, to: :country, prefix: true, allow_nil: true
# omitted...
end
如何告诉 rails 使用 edavis_id 作为 ID(而不是常规的 table ID)?
只需添加:
class Representation < ActiveRecord::Base
self.primary_id = :edavis_id
#...
end
尝试:
class Representation < ActiveRecord::Base
self.primary_key = :edavis_id
#
end
http://ruby-journal.com/how-to-override-default-primary-key-id-in-rails/