我在这里需要帮助
我在模型A::B
上具有以下关联
# Model A::B
belongs_to :B
当我尝试在数据库中创建/插入新的A :: B实例
# test.log
Processing by A::BController#create as HTML
Parameters: {"a_b"=>{"b_id"=>"128"}}
BEGIN
A::B Load (0.4ms) SELECT "a_b".* FROM "a_b" WHERE "a_b"."id" = $1 LIMIT [["id", 128], ["LIMIT", 1]]
ROLLBACK
如您所见,由于Rails在错误的类(A :: B而不是B)中进行搜索,因此我正在回滚,因此在数据库中找不到正确的元素。视图中生成的错误消息是B is required
。
# schema.rb
create_table "a_b", force: :cascade do |t|
t.bigint "b_id"
t.index ["b_id"], name: "index_a_b_on_b_id"
end
add_foreign_key "a_b", "b"
我认为问题与所用名称有关。由于某种原因,Rails在寻找关联时会考虑A::B
和B
相同。
我已经尝试在关联中传递选项class_name: 'B'
,但是它仍然使用错误的类。
为澄清起见,这些类的真实名称是:
A => edital
B => cargo
A::B => edital_cargo # (using namespace)
从Rails控制台:
# The association for the class Edital::Cargo
Edital::Cargo.reflect_on_association(:cargo)
=> #<ActiveRecord::Reflection::BelongsToReflection:0x00005588f76e6f60 @name=:cargo, @scope=nil, @options={:class_name=>"Cargo"}, @active_record=Edital::Cargo (call 'Edital::Cargo.connection' to establish a connection), @klass=nil, @plural_name="cargos", @type=nil, @foreign_type=nil, @constructable=true, @association_scope_cache=#<Concurrent::Map:0x005588f76e6588 entries=0 default_proc=nil>>
# Below, how Rails generate the names (@element and @human are equal for both)
ActiveModel::Name.new(Cargo)
=> #<ActiveModel::Name:0x00007fc6285f2a80 @name="Cargo", @klass=Cargo (call 'Cargo.connection' to establish a connection), @singular="cargo", @plural="cargos", @element="cargo", @human="Cargo", @collection="cargos", @param_key="cargo", @i18n_key=:cargo, @route_key="cargos", @singular_route_key="cargo">
ActiveModel::Name.new(Edital::Cargo)
=> #<ActiveModel::Name:0x00007fc6285d28c0 @name="Edital::Cargo", @klass=Edital::Cargo (call 'Edital::Cargo.connection' to establish a connection), @singular="edital_cargo", @plural="edital_cargos", @element="cargo", @human="Cargo", @collection="edital/cargos", @param_key="edital_cargo", @i18n_key=:"edital/cargo", @route_key="edital_cargos", @singular_route_key="edital_cargo">
有人已经面临这个问题吗?我只能在选项class_name
中考虑可以指定模型的地方。