我有模特:
Category
:
class Category < ActiveRecord::Base
has_many :entities, as: :resourcable
end
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :name
t.text :short_descr
t.text :full_descr
t.timestamps
end
end
end
Language
:
class Language < ActiveRecord::Base
has_many :entities, as: :resourcable, dependent: :destroy
validates :code, uniqueness: true
end
class CreateLanguages < ActiveRecord::Migration
def change
create_table :languages do |t|
t.string :name
t.string :code
t.timestamps
end
end
end
Entity
:
class Entity < ActiveRecord::Base
belongs_to :language
belongs_to :resourcable, polymorphic: true
end
class CreateEntities < ActiveRecord::Migration
def change
create_table :entities do |t|
t.integer :language_id
t.string :name
t.text :short_descr
t.text :full_descr
t.references :resourcable, polymorphic: true
t.timestamps
end
end
end
在Categories
中,字段(short_descr
,full_descr
)有默认值,在Entities
中有此字段的翻译。我需要使用适当的翻译以json
全部Categories
呈现:首先,我需要Language
使用适当的code
(例如ru
),然后,我需要找到此语言的所有语言Entities
,接下来,如果Entity
已填满short_descr
和full_descr
我需要使用此值呈现Category
,否则我需要使用默认值(Category
表中的此值)呈现Categories
。这该怎么做?我更喜欢ActiveRecord购买考虑纯SQL。
EDITED
现在我尝试使用gem 'squeel'
:
Language.joins{entities.category}.
select{coalesce(entities.short_descr, categories.short_descr)}.
where{languages.code == 'en'}
但它不起作用(undefined method
short_descr&#39;对于nil:NilClass`)。有问题吗?
答案 0 :(得分:0)
Entity.joins(:language, :category).
select('categories.*, coalesce(entities.short_descr, categories.short_descr) as short_descr,
coalesce(entities.full_descr, categories.full_descr) as full_descr').
where('languages.code = ?', 'en')