0

外部キー属性を持つオブジェクトを保存しようとしています。なぜ機能しないのかわかりません。外部キーは、データベースでnullではないと定義されています。

class Store < ActiveRecord::Base
  attr_accessible :latitude, :longitude, :description
  validates :store_group, :presence => true
  validates :description, :presence => true, :length => {:maximum => 500}
  validates :latitude,    :presence => true
  validates :longitude,   :presence => true

  belongs_to :store_group
end

class StoreGroup < ActiveRecord::Base
  attr_accessible :name, :description, :image
  validates :name, :presence => { :message => "Store group can not be empty" }
end

だから、私は店を保存しようとしています:

group = StoreGroup.new(:name=>"name",:description=>"description",:image=>"image")
store = Store.new(:store_group=>group,:latitude=>1,:longitude=>1,:description=>"description")
store.save

ただし、MySQLでは例外が発生します。

Mysql2::Error: Column 'store_group' cannot be null: INSERT INTO `stores` (`created_at`, `store_group`, `description`, `latitude`, `longitude`, `updated_at`) VALUES ('2013-02-17 04:09:15', NULL, 'description', 1.0, 1.0, '2013-02-17 04:09:15')

なんで?前もって感謝します :)

4

2 に答える 2

0

has_many :storesまず、たとえば、特定のStoreGroupに属するすべてのストアを取得する場合など、StoreGroupにを追加すると、長期的には簡単になる可能性があります。次に、StoreGroupを介してストアを追加する必要があります。すでに関連付けが行われているため、かなり簡単です(への変更に注意してくださいStore.create)。

group = StoreGroup.create(name: "name", description: "description", image: "image")
group.stores << Store.create(lat: 1, long: 1, desc: "description")

:store_group_idこのメソッドは、新しいStoreインスタンスをそのStoreGroupの「子」として自動的に設定して保存します。後で既存のStoreGroupsにストアを追加できるように、既存のStoreGroupsを考慮してコードを変更することもできます。.first_or_createRails 3.2.xでは、 with句を使用するの.where(...)は慣用的ですが、以前のバージョンのRailsには作成権限を持つ動的なファインダーがあります(例として、find_or_create_by_name_and_store_group_id)。

最後に、validates :store_group関連付けの検証がそのように機能しないため、削除します。本当に必要な場合は、を使用してvalidates :store_group_idください。

于 2013-02-17T05:23:09.700 に答える
0

store_groupを介してオブジェクトを作成/保存しようとしていますstore。したがって、以下を使用します。

accepts_nested_attributes_for :store_group

あなたのStoreモデルで

accepts_nested_attributes_forについてはこちらをお読みください

于 2013-02-17T05:42:57.693 に答える