我有以下设置:
class User < ActiveRecord::Base
has_many :device_ownerships, :dependent => :destroy
has_many :devices, :through => :device_ownerships
end
class device < ActiveRecord::Base
has_one :device_ownership, :dependent => :destroy
has_one :user, :through => :device_ownership
end
class deviceOwnership < ActiveRecord::Base
belongs_to :user
belongs_to :device
validates_uniqueness_of :device_id, :scope => :user_id
validates_uniqueness_of :user_id, :scope => :device_id
end
我正在尝试在Active Admin中实现以下目标:
在编辑屏幕中
1)列出属于用户的所有设备,并带有删除设备或销毁将设备连接到用户的
deviceOwnership
选项2)可以选择从现有设备创建新的配对用户设备(通过创建新的
DeviceOwnership
)。3)可以选择创建新设备,并通过新的
DeviceOwnership
将其添加到用户。我在下面的评论中列出了我现在遇到的问题:
ActiveAdmin.register User do
permit_params :email, :password, :password_confirmation, :role,
device_ownerships_attributes: [:device_id, :user_id],
devices_attributes: [:device_identifier]
index do |user|
user.column :email
user.column :current_sign_in_at
user.column :last_sign_in_at
user.column :sign_in_count
user.column :role
actions
end
filter :email
form do |f|
f.inputs "User Details" do
f.input :email
f.input :password
f.input :password_confirmation
f.input :role, as: :radio, collection: {Editor: "editor", Moderator: "moderator", Administrator: "administrator"}
#This one allows to create new devices but also lists all existing devices with option to modify their device_identifier column which I don't want
f.has_many :devices, :allow_destroy => true, :heading => 'Themes', :new_record => true do |cf|
cf.input :device_identifier
end
#This one lists all the devices but no option to remove any of them.
f.input :devices
#This one shows dropdownw with existing devices but allows to swap them
f.has_many :devices, :allow_destroy => true do |device_f|
device_f.input :device_identifier, :as => :select, :collection => device.all.map{ |device| [device.device_identifier] }, include_blank: false,
end
f.actions
end
end
end
最佳答案
线
f.has_many :devices, :allow_destroy => true, :heading => 'Themes', :new_record => true do |cf|
cf.input :device_identifier
end
看起来可以完成这项工作。您可以检查cf.object是否为新记录,并且在这种情况下仅允许用户更改
device_identifier
。cf.input :device_identifier if cf.object.new_record?
或类似
cf.input :device_identifier, input_html: { readonly: !cf.object.new_record? }
你怎么看?
关于ruby-on-rails - 通过Active Admin中的关联添加和列出has_many,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26634796/