【问题标题】:Testing an association with an alias_attribute使用 alias_attribute 测试关联
【发布时间】:2016-10-03 01:32:12
【问题描述】:

我计划为我的几个模型关联使用别名属性。 注意:我完全知道我也可以通过以下方式别名此关联:

belongs_to :type, class_name: "AlbumType"

但想进一步探索alias_attribute 方法。考虑到这一点,我有一个属于AlbumTypeAlbum

class Album < ApplicationRecord
  alias_attribute :type, :album_type
  belongs_to :album_type
end

class AlbumType < ApplicationRecord
  has_many :albums
end

到目前为止一切顺利。我现在想在我的专辑规范中测试别名关联。即使在指定类名之后,传统的belongs_to shoulda-matcher 似乎也不够聪明,无法识别 typealbum_type。我当然不反对编写传统的 RSpec 测试,但不确定在这种情况下如何。任何帮助将不胜感激。

RSpec.describe Album, type: :model do
  describe "ActiveRecord associations" do
    it { should belong_to(:album_type) }

    context "alias attributes" do
      it { should belong_to(:type).class_name("AlbumType") }
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails activerecord rspec alias


    【解决方案1】:

    我不建议为此使用alias_attribute。据我所知,shoulda 使用ActiveRecord::Reflection 来调查关联。 alias_attribute 所做的唯一事情是创建方法,通过 getter、setter 和“?”将消息从目标代理到源。方法。它显然是为了使用 ActiveRecord 属性而不是通用方法。

    这样做的效果是alias_attribute 不会将这些目标注册为 ActiveRecord 关联,shoulda 的当前实现将无法捕获它们。

    这种模式也有副作用。您可能知道,当您创建关联时,ActiveRecord 还会创建帮助方法以使您的生活更轻松。例如,belongs_to 也会创建:

    build_association(attributes = {})
    create_association(attributes = {})
    create_association!(attributes = {})
    

    以您的示例为例,使用alias_attribute 不会给您album.build_album_type,这是其他贡献者可能愿意依赖的东西,因为他们希望这是默认行为。

    处理此问题的最佳方法正是您告诉您不想做的事情,使用belongs_to 方法以您真正想要的名称创建关联。

    【讨论】:

    • 感谢您为我解决这个问题。目前正在设置我的 ActiveModel 序列化程序,所以这是在紧要关头。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2023-03-10
    相关资源
    最近更新 更多