在Rails,如果你想要使用自訂的Primary Key Name(主鍵)的話(如果你用Migrate產生,預設就會建立一個叫作id的主鍵)可以使用set_primary_key在Rails,如果你想要使用自订的Primary Key Name(主键)的话(如果你用Migrate产生,预设就会建立一个叫作id的主键)可以使用set_primary_key
set_primary_key好像還要搭配set_table_name使用,不然會出錯! set_primary_key好像还要搭配set_table_name使用,不然会出错!
因為我在作補習班網站的案子時,僅僅加入set_primary_key就出錯,加上set_table_name才正常,因此我想set_primary_key一定要有set_table_name的輔助吧?因为我在作补习班网站的案子时,仅仅加入set_primary_key就出错,加上set_table_name才正常,因此我想set_primary_key一定要有set_table_name的辅助吧? 不過反之我想應該不同!不过反之我想应该不同!
請在Model裏面編輯请在Model里面编辑
set_table_name “tbl_name” set_table_name “tbl_name”
set_primary_key “pk_name set_primary_key “pk_name
但是請注意!但是请注意! 如果自訂Primary Key的話,在編輯的欄位內請不要讓那個欄位可以編輯!如果自订Primary Key的话,在编辑的栏位内请不要让那个栏位可以编辑! 假設我...假设我...
set_table_name "people" set_table_name "people"
set_primary_key "uid" set_primary_key "uid"
此時就別讓uid可以編輯,像是出現:此时就别让uid可以编辑,像是出现:
<%= text_field "person", "uid" %> <%= text_field "person", "uid" %>
這樣會產生錯誤!这样会产生错误!
詳情可以參考:详情可以参考:
Agile Web Development with Rails書中第14章第三節的部份,雖然繼續使用uid還是可以的,但是會比較麻煩點! Agile Web Development with Rails书中第14章第三节的部份,虽然继续使用uid还是可以的,但是会比较麻烦点!
而該節最後一句話:When you need to set the primary key, use id. At all other times, use the actual column而该节最后一句话:When you need to set the primary key, use id. At all other times, use the actual column
感謝China on Rails群組中的darren.hoo!感谢China on Rails群组中的darren.hoo!
相關討論請看:相关讨论请看:
Ruby on Rails on Google Groups
Sets the name of the primary key column to use to the given value, or ( if the value is nil or false ) to the value returned by the given block.
Example:
Class Project class Project < ActiveRecord::Base
set_primary_key "sysid"
end
[ hide source ]
# File vendor/rails/activerecord/lib/active_record/base.rb, line 1011
1011: def set_primary_key(value = nil, &block)
1012: define_attr_method :primary_key, value, &block
1013: end