【发布时间】:2014-04-24 11:02:44
【问题描述】:
我有模型:
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 中有此字段的翻译。我需要将所有Categories 渲染为json 并带有适当的翻译:首先,我需要将Language 与适当的code(例如ru)一起使用,接下来,我需要找到所有语言Entities对于这种语言,接下来,如果Entity 填充了short_descr 和full_descr,我需要用这个值渲染Category,否则我需要用默认值渲染Category(Categories 表中的这个值)。这该怎么做?我更喜欢 ActiveRecord 购买考虑纯 SQL。
已编辑
现在我正在尝试使用gem 'squeel':
Language.joins{entities.category}.
select{coalesce(entities.short_descr, categories.short_descr)}.
where{languages.code == 'en'}
但它不起作用(undefined methodshort_descr' for nil:NilClass`)。有问题吗?
【问题讨论】:
标签: ruby-on-rails postgresql activerecord ruby-on-rails-4 rails-activerecord