我有一个模型订单。在索引中,我希望current_user只看到其订单的索引。订单belongs_to:admin_user。AdminUser has_many:表示订单。我在我的应用程序中使用activeadmin,如果这有所不同。我得到这个错误:
Couldn't find Order without an ID
给出错误的行是我的订单控制器中的第二行。(删除不必要的信息)
index do
@order = Order.where(admin_user_id: current_admin_user.id, order_id: resource.id)
column "ID" do |order|
link_to order.id, admin_order_path(order)
end
column "Proof" do |order|
image_tag order.proof_url(:proof).to_s
end
column "Name" do |order|
link_to order.name, admin_order_path(order)
end
column(:customer, :sortable => :customer_id)
column "Category", :order_category
column "Status", :order_status
column "Priority", :order_priority
column "Due Date", :end_date
default_actions
end
这是@jamesw请求的订单模型
class Order < ActiveRecord::Base
attr_accessible :color_back, :color_front, :color_sleeve, :end_date, :name, :start_date, :whiteboard, :customer_id, :order_category_id, :order_type_id, :order_status_id, :order_priority_id, :print_location_id, :artwork, :proof, :line_items_attributes, :assignee_id, :admin_user_id
mount_uploader :artwork, ArtworkUploader
mount_uploader :proof, ProofUploader
has_many :line_items
belongs_to :assignee, :class_name => "AdminUser"
belongs_to :customer
belongs_to :order_category
belongs_to :order_type
belongs_to :order_status
belongs_to :order_priority
belongs_to :print_location
belongs_to :admin_user
accepts_nested_attributes_for :line_items, :allow_destroy => true
scope :owned_by, lambda { |user| includes(:assignee).where("admin_users.id = ?", user.id) }
def default_values
if new_record?
self.start_date ||= Date.today
self.number ||= (Order.maximum(:number) + 1 rescue 1)
end
end
end
看起来您正在尝试按order_id
过滤Orders表。除非您以非标准方式构建数据库,否则订单表的ID字段通常是id
(而不是order_id
)。
把这个问题放在一边,我怀疑您是否想要为索引操作传递一个订单id,因为这只会返回一条记录,而且索引操作的本质应该列出许多记录(在您的情况下,是current_admin_user的所有记录)。
如果这两个问题都不能解决您的问题,请尝试逐行注释。
尝试添加此控制器方法
ActiveAdmin.register Order do
controller do
def scoped_collection
Order.where(:admin_user => current_admin_user.id)
end
end
end
在这里看到更多:同一资源的两个页面- ActiveAdmin
我通过取出有问题的行并使用scope_to :current_user
解决了这个问题。我想知道,虽然,如何添加一个条件语句,仍然允许管理员查看这个?现在我们来看一下控制器。
scope_to current_user
index do
column "ID" do |order|
link_to order.id, admin_order_path(order)
end
column "Proof" do |order|
image_tag order.proof_url(:proof).to_s
end
column "Name" do |order|
link_to order.name, admin_order_path(order)
end
column(:customer, :sortable => :customer_id)
column "Category", :order_category
column "Status", :order_status
column "Priority", :order_priority
column "Due Date", :end_date
default_actions
end