私は6ヶ月以来3 &のレールで作業していましたが、 "文字列"列を主キーとしてどのように実装できるかについてはまだ分かりません。私はそれが非整数フィールドがMySQLのテーブルのプライマリキーになることを許可していないと思います。 たとえば、 customer_code:stringをプライマリキーとして持つ顧客テーブルがある場合& customer_codeフィールドを使用してcustomerテーブルを参照するproductsテーブル、つまりproductsテーブルのcustomer_codeは外部キーです。レール3にこの関係を実装するにはどうすればよいですか? 誰も私にこの関係を実装するための適切な方法を提案できますか?rails 3 mysql relationships
0
A
答えて
0
私は物事をシンプルにし、標準的なレールの規則に従います - あなたのキーの自動IDフィールドを使用してください。
コードを取得するためにユーザーオブジェクトをルックアップする必要がないように、製品テーブルにcustomer_codeを設定する場合は、製品を保存するときにこれも保存します。
0
Costumer
とProducts
の2つのモデルがあります。だからこのソリューションはどうですか?落とし穴に
class Costumer < AR::Base
set_primary_key 'code'
has_many :products, :foreign_key => :costumer_code
validates :code, :presence => true
end
class Product < AR::Base
belongs_to :costumer, :foreign_key => :costumer_code
end
は、それがid
キーデフォルトのプライマリのような自動インクリメントではありませんので、あなたは、コードが正しく作成時に設定されているのcostumersを確保しなければならないということです。 before_create
コールバックが役に立ちます。
0
class Product < ActiveRecord::Base
belongs_to :customer, :foreign_key => :customer_code, :primary_key => :customer_code
end
関連する問題
- 1. Rails "Sometimes Has One" Relationships
- 2. Rails 3 MySql and MongoDB
- 3. Rails 3.x MySQL Monitor/Reviewer
- 4. Laravel Elevent relationships
- 5. Laravel Eloquent querying relationships
- 6. laravel eloquent relationshipsエラー
- 7. Gorm and relationships
- 8. rails table relationships:関連する値を出力する方法は?
- 9. Railsの3 - ActiveRecordの+ MySQLとRANDOM機能
- 10. Mysql to PostgreSql Rails 3 heroku app true/false
- 11. MySQL GemとRails 3(Lion 10.7)のインストール
- 12. Rails 3のマイグレーション:boolean(mysql vs postgreSQL)
- 13. Laravel Eloquent Relationships - MYSQLの "join"に相当する
- 14. Rails 3 - rails-dbd-mysql gemはmysql2ではなくmysqlに依存します
- 15. Rails 3テーブルロック
- 16. Rails 3 - Rails 3アプリでS3
- 17. jQuery in Rails 3 "Beginning Rails 3"
- 18. Ellquent Relationships、モデルのリンク(Laravel 5.4)
- 19. Laravel EloquentとrelationshipsのsetTable()
- 20. Rails 3のスクリーンスクレイピング3
- 21. Rails 3
- 22. Rails 3 Coffee Handler Missing
- 23. Rails make database mysql
- 24. PGError:ERROR:relation "companies"が存在しません(postgresql、mysql、rails 3)
- 25. Rails 3:動的ベースのMySQLクエリのパラメータをループする
- 26. Rails 3:無限のSQLクエリ?
- 27. Railsの3:モデル
- 28. Rails 3 ActiveRecord Localization
- 29. Rails 3 Rounting changes
- 30. Rails 3. Distinct query
「before_filter」ではなく「before_create」または「before_save」です。フィルタはコントローラ内にあります。 – RocketR
うん、そう。もちろんbefore_createコールバックです。 –