Rails的HAS_MANY通过多态复选框
-
25-09-2019 - |
题
这一个真的让我失望! :(
我试图做一个嵌套的模型形式为我在里面有一个复选框列表,其中多个商店,可以选中或取消选中通过模型人员配备来管理存储的用户模型。
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"=>"test@hey.net",
"role"=>"admin",
"hq"=>"1",
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]",
"store_ids"=>["3",
"4"]}}
和然后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)
我知道我必须打造出staffable_type为“商店”,但我已经了一整天 - 有什么诀窍
?我确实有staffable_type(和id)设置为列:空=>假但不能为这个原因,以在控制器击中DB反正之前进行梳理此需要
为什么在我创建行动以下不工作:
@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
如果在尝试上述无济于事类似的东西。任何帮助,将大规模理解。
感谢您的时间!
解决方案
好,我想通这一个。我回答在这里,所以我希望能帮助别人一天,但问题是在差异基本监督之间有许多通过,并已属于许多联想。
您如果要处理复选框或多项选择列表中有许多通过,不存在通过关联为您生成“_ids”的方法,你需要写一个自己。
请参阅保罗·巴里的文章在这里: http://paulbarry.com/articles/2007/10/24/has_many - 通过-复选框
多态的东西可能会很复杂,但如果你坚持真正的好,也许退一步,并确保它不是一些更基本的是搞乱真实您up--为我工作!
下面是关于如何处理这个,如果你正在处理一个多态有许多通过(基本上你只需要使用属性散列和编写polymorphic_type属性)从保罗的博客修改的代码:
attr_accessor :store_ids
after_save :update_stores
#after_save callback to handle group_ids
def update_stores
unless store_ids.nil?
self.staffings.each do |staffing|
staffing.destroy unless store_ids.include?(staffing.staffable_id.to_s)
store_ids.delete(staffing.staffable_id.to_s)
end
store_ids.each do |s|
self.staffings.create(attributes = {:staffable_id => s, :staffable_type => 'Store'}) unless s.blank?
end
reload
self.store_ids = nil
end
end
不隶属于 StackOverflow