Rails Admin has_many关联选项删除自定义
我想在Rails管理员选择下拉选项中进行一些更改。我有一些具有has_many关系的模型。
模型文件 post.rb
class Post < ApplicationRecord
has_many :photos, dependent: :destroy
accepts_nested_attributes_for :photos, allow_destroy: true
def post_image
photos&.first&.asset_url
end
end
photo.rb
class Photo < ApplicationRecord
belongs_to :post
end
homepage.rb
class Homepage < ApplicationRecord
has_many :homepagepost
has_many :posts,-> { order(likes_count: :desc) }, through: :homepagepost
end
homepagepost.rb
class Homepagepost < ApplicationRecord
belongs_to :post
end
设置管理员配置 rails_admin.rb
config.model Homepage do
label "Homepage Rows"
edit do
field :title_heading
field :posts
field :status
end
list do
field :title_heading
field :posts
field :status
field :created_at
field :updated_at
end
end
现在,我想在带有帖子ID的“帖子”下拉列表中显示帖子图像URL。我如何在Rails管理员中执行此操作? 就像 Post#1370 post_test.png
架构
create_table "photos", id: :serial, force: :cascade do |t|
t.string "asset_url"
t.integer "post_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["post_id"], name: "index_photos_on_post_id"
end
create_table "posts", id: :serial, force: :cascade do |t|
t.integer "user_id"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_posts_on_user_id"
end
create_table "homepageposts", force: :cascade do |t|
t.integer "homepage_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "post_id"
t.index ["post_id"], name: "index_homepageposts_on_post_id"
end
create_table "homepages", force: :cascade do |t|
t.string "title_heading"
t.integer "status"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
答案 0 :(得分:1)
首先在rails admin初始化程序上进行配置,通常是在配置块内的config/initializers/rails_admin.rb
上进行配置,该方法将在模型中用于确定要为每个对象显示的标题,如下所示:
RailsAdmin.config do |config|
config.label_methods = [:rails_admin_title]
end
然后在您的帖子模型上定义该方法
class Post < ApplicationRecord
has_many :photos, dependent: :destroy
accepts_nested_attributes_for :photos, allow_destroy: true
def rails_admin_title
"<a href='#{post_image}'>Link</a>".html_safe
end
def post_image
photos&.first&.asset_url
end
end
您可能需要重新启动开发服务器才能看到此更改。