[Rails]ActiveAdmin常見語法(1)

in cn •  6 years ago  (edited)

在後台建立新的model對應的頁面

$ rails g active_admin:resource NewModelName

更改admin route

# config/initailizer.rb/active_admin.rb
config.default_namespace = :your_new_admin_route
# change it to the name your want

登入後台的路徑就會變成

localhost:3000/your_new_admin_route

Resource: How can I change the default url of activeadmin

在show page顯示圖片

row :product_img do |obj|
  image_tag obj.product_img.url
end
# 或是

row(:product_img) { |obj| image_tag obj.product_img.url }

Resource: Customize the index page
Resource: Rails: Active Admin Association Image column

使用預設strong parameter

ActiveAdmin.register Post do
  permit_params :title, :content
end

更改model中預設的objects

舉例來說,在admin/loans.rb的檔案下,會預設使用@loans = Loan.all

但如果你想要客製化@loans的話,可以透過scope_collection設定得到的object。

ActiveAdmin.register Loan do
  controller do
    def scoped_collection
      Loan.where(aasm_state: :paid)
    end
  end
end

設定欄位寬度

set column_width

colums do
  column max_width: "200px", min_width: "100px" do
    span "Column # 1"
  end
end

使用group selection

make group option select in activeadmin

f.input :product_id, as: :select, collection: option_groups_from_collection_for_select(Category.all, :products, :name, :id, :product_code), :wrapper_html => { :class => 'fl product_code'}, include_blank: false

Resource: option_groups_from_collection_for_select
Resource: option_groups_from_collection_for_select.rb
Resource: Formtastic select with grouping

設定show page title

更多page title設置方法請參考
Set Page Title

# Custom string
index :title => 'Awesome Title' do
  # ...
end
# Call a method
show :title => :my_title_method do
  # ...
end
# execute some code
show :title => proc{|post| post.title } do
   # ...
end

設定collection和member action

ActiveAdmin.register Carton do
  member_action :member_action, method: :post do
    # do something
  end

  collection_action :collection_action, method: :get do
    # do something
  end
end

以上兩個method除了會幫你在controller建立method外,還會同時幫你設定routes。

$ rails routes | grep carton
collection_action_admin_cartons GET        /admin/cartons/collection_action(.:format)                   admin/cartons#collection_action
memeber_action_admin_cartons POST        /admin/cartons/:id/member_action(.:format)                   admin/cartons#member_action

Resource: Custom Controller Action

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!