Sur*_*oza 1 ruby polymorphism ruby-on-rails polymorphic-associations activeadmin
我正在与 Active Admin 合作。目前,我有一个索引页面,允许我查看用户标记的所有资源。鉴于存在各种类型的资源,我的 Flagg 类和各种资源表之间存在多态关系。
在我的索引页面中,在 Active Admin 上,我希望能够链接到属于特定资源类型的相应显示页面。
我已经让我所有的代码都能工作了,但我不喜欢我想出的解决方案。
我如何改进我当前的解决方案,这样我就不必写一个尴尬的条件?
楷模
class Flag < ActiveRecord::Base
#create relationships with user and flag model
belongs_to :flaggable, polymorphic: true
end
class MilitaryResource < ActiveRecord::Base
has_many :flags, as: :flaggable, :dependent => :destroy
end
class DistrictResource < ActiveRecord::Base
has_many :flags, as: :flaggable, :dependent => :destroy
end
class SchoolResource < ActiveRecord::Base
has_many :flags, as: :flaggable, :dependent => :destroy
end
Run Code Online (Sandbox Code Playgroud)
活动管理员
ActiveAdmin.register Flag do
#parameters permitted to create military resources
permit_params :id, :user_id, :flaggable_id, :flaggable_type, :message, :created_at
#index page
index do
column :flaggable_type
###Current Solution
column "Flagged Resource" do |site|
if site.flaggable_type == "MilitaryResource"
link_to site.flaggable.name, :controller => "military_resources", :action => "show", :id => "#{site.flaggable_id}".html_safe
elsif site.flaggable_type == "SchoolResource"
link_to site.flaggable.name, :controller => "school_resources", :action => "show", :id => "#{site.flaggable_id}".html_safe
elsif site.flaggable_type == "DistrictResource"
link_to site.flaggable.name, :controller => "district_resources", :action => "show", :id => "#{site.flaggable_id}".html_safe
end
end
column :message
actions
end
Run Code Online (Sandbox Code Playgroud)
小智 6
你可以做这样的事情来避免条件:
column "Flagged Resource" do |site|
link_to site.flaggable.name,
:controller => site.flaggable_type.underscore.pluralize,
:action => "show",
:id => "#{site.flaggable_id}"
.html_safe
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1032 次 |
| 最近记录: |