2016-10-03 68 views
3

我打算为几个模型关联使用别名属性。 注:我完全知道,我也别名通过这种关联:测试与alias_attribute的关联

belongs_to :type, class_name: "AlbumType" 

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

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

class AlbumType < ApplicationRecord 
    has_many :albums 
end 

到目前为止好。我现在想在我的相册规范中测试别名关联。看起来,即使在指定了类名之后,传统的应该匹配器也不足以识别类型album_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 

回答

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方法以你真正想要的名称创建关联。

+0

感谢您为我清理。目前正在设置我的ActiveModel序列化器的过程中,所以这是一个时间。 –