我有一个简单的表单来显示具有has_many关系的模型。
form do |f|
f.semantic_errors *f.object.errors.keys
f.inputs do
f.has_many :messages, allow_destroy: true, heading: 'Messages' do |f|
f.input :title
end
end
f.actions
end
我的问题是:如何预过滤:显示来自之前的消息? 它取决于current_admin用户。
答案 0 :(得分:1)
NeverBe!
我的解决方案基于创建与模型条件的自定义has_many关系。 例如:
文件/app/models/key.rb
class Key < ActiveRecord::Base
attr_accessible :name,
:messages, :messages_attributes,
:messages_for_organization_attributes
has_many :messages, dependent: :destroy
accepts_nested_attributes_for :messages, allow_destroy: true
has_many :messages_for_organization, class_name: 'Message', conditions: proc {"organization_id" = #{$current_admin_user.organization_id}"}
accepts_nested_attributes_for :messages_for_organization, allow_destroy: true
end
文件/app/models/message.rb
class Message < ActiveRecord::Base
attr_accessible :title,
:key, :key_id
:organization, :organization_id
belongs_to :key
belongs_to :organization
end
文件app / admin / key.rb:
controller do
def edit
if current_admin_user.role?('super_admin')
@key = Key.find_by_id(params[:id])
else
@key = Key.joins('LEFT JOIN messages ON messages.key_id = key.id').where(id: params[:id]).first
end
$current_admin_user = current_admin_user # Important assignment to get access current_admin_user in Key model class
edit!
end
end
form do |f|
f.semantic_errors *f.object.errors.keys
f.inputs do
if current_admin_user.role?('super_admin')
f.has_many :messages, allow_destroy: true, heading: 'Messages' do |f|
f.input :title
end
else
f.has_many :messages_for_organization, allow_destroy: true, heading: 'Messages' do |f|
f.input :title
end
end
end
f.actions
end