这一个真的让我失望! :(Rails有许多通过多态复选框
我试图做一个嵌套的模型形式为我在里面有一个复选框列表,其中多个商店,可以选中或取消选中通过模型人员配备来管理存储的用户模型。
class Staffing < ActiveRecord::Base
# Associations
belongs_to :user
belongs_to :staffable, :polymorphic => true
belongs_to :store, :class_name => "Store",
:foreign_key => "staffable_id"
end
class User < ActiveRecord::Base
# Includes
acts_as_authentic
# Associations
has_many :staffings, :dependent => :destroy
has_many :stores, :through => :staffings
# Nested Attributes
accepts_nested_attributes_for :staffings, :allow_destroy => true
end
class Store < ActiveRecord::Base
# Associations
has_many :staffings, :as => :staffable, :dependent => :destroy
has_many :users, :through => :staffings
end
# Users Controller
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
对于其他staffable协会可以忽略不计的目的在眼前。这是一个类似的模型,我最终想要第一旁边商店,但第一件事的管理,因为我很为难,因为它是。
# User Form
- for store in Store.all
%p
= check_box_tag "user[store_ids][]", store.id, @user.stores.include?(store)
= store.nickname
发送我的PARAMS沿着这样的:
{"utf8"=>"✓",
"authenticity_token"=>"blub-blub-blub=",
"user"=>{"login"=>"hey.buddy",
"email"=>"[email protected]",
"role"=>"admin",
"hq"=>"1",
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]",
"store_ids"=>["3",
"4"]}}
然后错误!
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)
我知道我必须打造出staffable_type为“商店”,但我已经了一整天 - 有什么诀窍?
我确实将staffable_type(和id)列设置为:null => false,但这不可能是造成这种情况的原因,因为无论如何都需要在控制器中将其清理出来。
为什么下面没有在我创建行动工作:
@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
如果一直试图与上述类似无济于事很多东西。任何帮助将大规模赞赏。
谢谢你的时间!