我想用拔毛法活動模型序列化一個對象關聯:使用拔毛串行
Post has_many :comments
有沒有辦法覆蓋
has_many :comments
在串行器使用採摘(:id,:標題)上的評論?
我想用拔毛法活動模型序列化一個對象關聯:使用拔毛串行
Post has_many :comments
有沒有辦法覆蓋
has_many :comments
在串行器使用採摘(:id,:標題)上的評論?
您可以使用has_many塊來擴展與方法的關聯。請參閱評論「使用塊來擴展您的關聯」here。
class Post < ActiveRecord::Base
has_many :comments do
def plucked()
select("id, title")
end
end
end
或其他方式,從相同的鏈接就可以了,有你的自定義SQL查詢獲取comments
從數據庫時:
has_many :comments, :class_name => 'Comment', :finder_sql => %q(
SELECT id, title
FROM comments
WHERE post_id = #{id}
)
在軌documentation,這表明,有一個選項:select
,也可以用於此目的。
我通常會在這種情況下做什麼,我有兩個不同的序列化器CommentSerializer
和CommentInfoSerializer
。因此CommentInfoSerializer
只包含我想要在其父資源的嵌入屬性中響應的最小屬性。
class CommentSerializer < ActiveModel::Serializer
attributes :id, :title, :body
end
class CommentInfoSerializer < ActiveModel::Serializer
attributes :id, :title
end
class PostSerializer < ActiveModel::Serializer
has_many :comments, serializer: CommentInfoSerializer
end
與設置評論序列化程序中的屬性不一樣嗎?我想在相關的評論中使用pluck,因爲它比具有活動記錄序列化評論對象的速度更快 –
您可以通過舉例說明您的最終目標是什麼,以及想要達到的目標。 – Saurabh
目標是獲取父對象的關聯對象。在這種情況下,通過郵政獲取評論。但是,由於有很多評論,試着通過在序列化程序中使用相關注釋來儘可能快地進行查詢。 –