我正在努力从某些 3.x 版本 4.0 升级 ransack,其中应该显式定义允许的 ransackable 属性,我已经修复了所有项目模型,但现在它在 Rails 核心模块上失败了。
# RuntimeError:
# Ransack needs ActionText::RichText attributes explicitly allowlisted as
# searchable. Define a `ransackable_attributes` class method in your `ActionText::RichText`
# model, watching out for items you DON'T want searchable (for
# example, `encrypted_password`, `password_reset_token`, `owner` or
# other sensitive information). You can use the following as a base:
#
# ```ruby
# class ActionText::RichText < ApplicationRecord
#
# # ...
#
# def self.ransackable_attributes(auth_object = nil)
# ["body", "created_at", "id", "locale", "name", "record_id", "record_type", "updated_at"]
# end
#
# # ...
#
# end
# ```
我已经尝试直接在源中重新打开类,但是 Rails 没有获取并忽略了这些更改。我试图在初始化期间找到一些配置更改,但这也不起作用。我打赌有人已经解决了从 3.0 到 4.x 的迁移
app/models/action_text/rich_text.rb
class ActionText::RichText < ApplicationRecord
# ...
def self.ransackable_attributes(auth_object = nil)
["body", "created_at", "id", "locale", "name", "record_id", "record_type", "updated_at"]
end
# ...
end
结果 -> 只是忽略,相同的问题 Rails 没有看到这些更改。
config/initializers/action_text.rb
class ActionText::RichText < ActiveRecord::Base
def self.ransackable_attributes(auth_object = nil)
["body", "created_at", "id", "locale", "name", "record_id", "record_type", "updated_at"]
end
end
初始化加载期间结果错误 ->
An error occurred while loading rails_helper.
Failure/Error: require File.expand_path('../config/environment', __dir__)
NoMethodError:
undefined method `has_many_attached' for ActionText::RichText:Class
# ./config/initializers/action_text.rb:7:in `<main>'
# ./config/environment.rb:5:in `<top (required)>'
# ./spec/rails_helper.rb:6:in `require'
# ./spec/rails_helper.rb:6:in `<top (required)>'
No examples found.
看起来你需要让日志说——明确定义建议的方法。既然有这样的继承:
ActionText::RichText < ActionText::Record < ActiveRecord::Base
,就可以在ActionText::RichText
的父类中定义这个方法
# config/initializers/action_text.rb
class ActionText::Record < ActiveRecord::Base
def self.ransackable_attributes(auth_object = nil)
authorizable_ransackable_attributes
end
end
也可以直接在
ActionText::RichText
类中的初始化器中定义此方法。但是'method_missing': undefined method 'has_many_attached' for ActionText::RichText:Class (NoMethodError)
(问题文本中的错误)可能会因为加载顺序而引发(此DSL方法尚不可用)
为了避免这种情况,你可以使用 ActiveSupport 钩子,它的名字可以在这里
找到在这种情况下,补丁将如下所示
# config/initializers/action_text.rb
ActiveSupport.on_load(:action_text_rich_text) do
class ActionText::RichText < ActionText::Record
def self.ransackable_attributes(auth_object = nil)
authorizable_ransackable_attributes
end
end
end
当然,您可以使用所需属性的显式数组(字符串数组)来代替
authorizable_ransackable_attributes
,例如%w[id body name record_id record_type]
等。