ActiveRecord:找到合适的翻译

时间:2014-04-24 11:02:45

标签: ruby-on-rails postgresql activerecord ruby-on-rails-4 rails-activerecord

我有模特: 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_descrfull_descr)有默认值,在Entities中有此字段的翻译。我需要使用适当的翻译以json全部Categories呈现:首先,我需要Language使用适当的code(例如ru),然后,我需要找到此语言的所有语言Entities,接下来,如果Entity已填满short_descrfull_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`)。有问题吗?

1 个答案:

答案 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')