It really turns me on! :(
I am trying to create a nested model model for my User model, having a list of flags in it, where several stores can be checked or unchecked to administer the repositories through the model.
class Staffing < ActiveRecord::Base
belongs_to :user
belongs_to :staffable, :polymorphic => true
belongs_to :store, :class_name => "Store",
:foreign_key => "staffable_id"
end
class User < ActiveRecord::Base
acts_as_authentic
has_many :staffings, :dependent => :destroy
has_many :stores, :through => :staffings
accepts_nested_attributes_for :staffings, :allow_destroy => true
end
class Store < ActiveRecord::Base
has_many :staffings, :as => :staffable, :dependent => :destroy
has_many :users, :through => :staffings
end
def create
@user = User.new(params[:user])
flash.now[:notice] = "#{@user.name} was successfully created." if @user.save
respond_with @user
end
def update
@user = User.find(params[:id])
params[:user][:store_ids] ||= []
@user.update_attributes(params[:user])
flash.now[:notice] = "#{@user.name} was successfully updated."
respond_with @user
end
For purposes that may be ignored, another personal association may be ignored. This is a similar model that I ultimately want to administer with the Store, but first at first, since I'm as dumb as possible.
- for store in Store.all
%p
= check_box_tag "user[store_ids][]", store.id, @user.stores.include?(store)
= store.nickname
Sends my parameters as such:
{"utf8"=>"✓",
"authenticity_token"=>"blub-blub-blub=",
"user"=>{"login"=>"hey.buddy",
"email"=>"test@hey.net",
"role"=>"admin",
"hq"=>"1",
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]",
"store_ids"=>["3",
"4"]}}
And then ERROR!
Mysql2::Error: Column 'staffable_type' cannot be null: INSERT INTO `staffings` (`created_at`, `staffable_id`, `staffable_type`, `updated_at`, `user_id`) VALUES ('2010-11-17 00:30:24', 3, NULL, '2010-11-17 00:30:24', 102)
I know that I need to create staffable_type as a "Store", but I tried all day - what's the trick?
staffable_type ( id), : null = > false, , , DB .
create:
@user.staffings.each do |s|
s.staffable_type = 'Store'
end
@user.store_ids.each do |i|
s = @user.staffings.build
s.staffable_type = 'Store'
s.staffable_id = i
end
, , . .
!