簡體   English   中英

Rails model #attributes 方法將 gem 插入關聯顯示為 model 屬性

[英]Rails model #attributes method shows gem inserted association as model attribute

我正在將 Rails 4.2 應用程序升級到 Rails 5.2 版。 我們正在使用acts_as_taggable_on gem(版本從4 更改為6)來實現標記功能。

假設我有一個名為 Task 的 model。 如果我執行Task.new ,我會得到以下初始化的 object。

=> #<Task:0x00003fh7398rcg3
 id: nil,
 title: nil,
 description: nil,
 creator_id: nil,
 due_date: nil
 status: "active",
 created_at: nil, 
 updated_at: nil>

如果我做Task.new.attributes ,我會得到

 {"id"=>"nil,
 "title"=>"nil,
 "description"=>"nil,
 "creator_id"=>"nil,
 "due_date"=>"nil
 "status"=>""active",
 "created_at"=>"nil, 
 "updated_at"=>"nil,
 "tag_list"=>nil}

tag_list來自 gem,預計將用於設置和更新關聯的標簽。

在 Rails 4.2 上,行為符合預期。 在 Rails 5.2 上,由於這個附加屬性顯示為 model 屬性,它會在多個地方引起意外問題。

我去查看並看到 ActiveRecord::ModelSchema 的更改可能是原因。

當我這樣做時,我在任務 model 上做了一個強制加載模式。

Task.send(:load_schema!)

Output:

{
"id"=>#<ActiveRecord::Type::UnsignedInteger:0x00007fc89f01d780 @limit=4, @precision=nil, @range=0...4294967296, @scale=nil>,
"title"=>#<ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter::MysqlString:0x00007fc89f0245f8 @limit=610, @precision=nil, @scale=nil>,
"description"=>#<ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter::MysqlString:0x00007fc8ab906d40 @limit=1000, @precision=nil, @scale=nil>,
"creator_id"=>#<ActiveRecord::Type::UnsignedInteger:0x00007fc89f01d780 @limit=4, @precision=nil, @range=0...4294967296, @scale=nil>,
"due_date"=>#<ActiveRecord::Type::DateTime:0x00007fc8ab90a5d0 @limit=nil, @precision=0, @scale=nil>,
"status"=>#<ActiveRecord::Enum::EnumType:0x00007fc8a0341870 @mapping={"active"=>0, 
"complete"=>1}, @name="status", ,@scale=nil>,@subtype=#<ActiveModel::Type::Integer:0x00007fc8ab908370 @limit=1, @precision=nil, @range=-128...128, @scale=nil>>,
"created_at"=>#<ActiveRecord::Type::DateTime:0x00007fc8ab90a5d0 @limit=nil, @precision=0, @scale=nil>,
"updated_at"=>#<ActiveRecord::Type::DateTime:0x00007fc8ab90a5d0 @limit=nil, @precision=0, @scale=nil>
"tag_list"=>#<ActsAsTaggableOn::Taggable::TagListType:0x00007fc89fe9e840 @limit=nil, @precision=nil, @scale=nil>
}

當我嘗試通過執行Task._default_attributes查看默認屬性時,我仍然看到 tag_list 屬性。

   "tag_list"=>
    #<ActiveModel::Attribute::WithCastValue:0x00007fc8a03409c0
     @name="tag_list",
     @original_attribute=nil,
     @type=#<ActsAsTaggableOn::Taggable::TagListType:0x00007fc89fe9e840 @limit=nil, @precision=nil, @scale=nil>,
     @value_before_type_cast=nil>}>

tag_list絕對不在 model 模式上,但無論如何它都顯示為這樣。

我很難過如何解決這個問題。 感謝任何幫助!

gem 導致了這種情況,因為您升級了 2 個主要版本,因此進行了很多更改。 可能這條線導致它https://github.com/mbleigh/acts-as-taggable-on/blob/950c01072b7ab6227d74dc0d0b112f0135281fc2/lib/acts_as_taggable_on/taggable/core.rb#L42 您的選擇是更改您的代碼以支持此更改,或者如果它支持 Rails 5,請嘗試運行較舊的 gem 版本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM