cie*_*bor 22 resources scope ruby-on-rails activeadmin
目前我有User
模型,它user.rb
作为ActiveAdmin的新资源注册.生成的页面显示具有范围(all
/ journalists
/ startup_employees
)的所有用户.现在我想创建另一个页面相同的资源,和相同的范围,但应该只记录与waiting
字段设置为true
(和以前的页面应该只有这与显示器:waiting => false
).我怎么能这样做?我知道我可以用过滤器做到这一点,但我需要两个单独的页面,菜单中有两个链接.
//解决方案
它甚至比建议更容易(谢谢你们!):
ActiveAdmin.register User, :as => 'Waitlist User' do
menu :label => "Waitlist"
controller do
def scoped_collection
User.where(:waitlist => true)
end
end
# code
scope :all
scope :journalists
scope :startup_employees
end
Run Code Online (Sandbox Code Playgroud)
ActiveAdmin.register User do
controller do
def scoped_collection
User.where(:waitlist => false)
end
end
# code
scope :all
scope :journalists
scope :startup_employees
end
Run Code Online (Sandbox Code Playgroud)
STI(单表继承)可用于创建相同表/父模型的多个"子资源"Active admin
在用户表中添加"type"列作为字符串
将其添加到User
模型以使用类型字段镜像等待字段
after_commit {|i| update_attribute(:type, waiting ? "UserWaiting" : "UserNotWaiting" )}
Run Code Online (Sandbox Code Playgroud)创建新模型UserWaiting
和UserNotWaiting
class UserWaiting < User
end
class UserNotWaiting < User
end
Run Code Online (Sandbox Code Playgroud)创建Active Admin
资源
ActiveAdmin.register UserWaiting do
# ....
end
ActiveAdmin.register UserNotWaiting do
# ....
end
Run Code Online (Sandbox Code Playgroud)您可以在控制台中运行首次同步
User.all.each {|user| user.save}
Run Code Online (Sandbox Code Playgroud)..............
另一种方法可以是跳过类型列(步骤1,2和5)并使用范围解决其余部分.
上面的步骤3和4
然后创建范围
#model/user.rb
scope :waiting, where(:waiting => true)
scope :not_waiting, where(:waiting => false)
Run Code Online (Sandbox Code Playgroud)范围 Active Admin
#admin/user.rb
scope :waiting, :default => true
#admin/user_not_waitings.rb
scope :not_waiting, :default => true
Run Code Online (Sandbox Code Playgroud)只需确保这两个页面中的其他范围也在wait/not_waiting上进行过滤
您可以使用参数来区分情况并根据参数呈现不同的操作:
link_to users_path(:kind => 'waiting')
Run Code Online (Sandbox Code Playgroud)
并在 users_controller.rb 中
def index
if params[:kind]=='waiting'
@users= Users.where(:waiting => true)
render :action => 'waiting' and return
else
# do your other stuff
end
end
Run Code Online (Sandbox Code Playgroud)
然后将您的新的不同页面(部分)放入 app/views/users/waiting.html.erb
如果您想为此页面使用不同的布局,请添加要渲染的布局参数:
render :action => 'waiting', :layout => 'other_layout' and return
Run Code Online (Sandbox Code Playgroud)