0

私は、ユーザーのタイプに応じて異なるテーブルを提供するRailsアプリを作成しようとしています。たとえば、在庫を担当しているとすると、アプリは在庫に関連するテーブルを表示します。問題は私ではありません。すべてのタイプのユーザーが存在することを事前に知っているので、問題に対する一般的な アプローチが必要です。

私の実際のユーザーモデルは次のようになります。

# == Schema Information
#
# Table name: users
#
#  id              :integer         not null, primary key
#  created_at      :datetime        not null
#  updated_at      :datetime        not null
#  password_digest :string(255)
#  remember_token  :string(255)
#  username        :string(255)
#  id_compania     :string(255)
#  type            :integer
#  name            :string(255)
#  admin           :boolean         default(FALSE)
#  empresa_id      :integer         default(1), not null
#

class User < ActiveRecord::Base
  attr_accessible :id_compania, :username, :type, :password, :password_confirmation, :name, :empresa_id
  has_secure_password
  belongs_to :empresa

  before_save { |user| user.username = username.downcase }
  before_save :create_remember_token
  USERNAME_REGEX = /(^([a-z]{3})-([a-z\d]){5,}$)/

  validates :username, `enter code here`presence: true, length: { maximum: 15 }, format: { with: USERNAME_REGEX }
  validates :password, presence: true, length: { minimum: 8 }
  validates :password_confirmation, presence: true
  validates :type, presence: true, length: { maximum: 4 }
  validates :id_compania, presence: true, length: { maximum: 3 }


  private

    def create_remember_token
      self.remember_token = SecureRandom.urlsafe_base64
    end

end
4

2 に答える 2

0

これには単一テーブル継承を使用します。スキーマに加える必要がある唯一の変更は、整数の代わりにタイプフィールドに文字列を使用することです。誰かがRailsガイド用のSTIガイドを作成しましたが、何らかの理由で完成しませんでした。あなたはそれから十分に得ることができるはずです、そしてstackoverflowはトピックに関するいくつかの素晴らしい質問と答えを持っています。

列を変更したら、ユーザーモデルのさまざまなサブクラスを作成する必要があります。

User < ActiveRecord::Base
end

InventoryUser < User
  def tables
    # your logic
  end
end

AdminUser < User
  def tables
    # your logic
  end
end
于 2012-07-21T00:58:18.377 に答える
0

したがって、ユーザーに対して :type が定義されているようです。その場合は、関心のあるユーザー タイプに応じて特定のテーブルを返すメソッドを定義できます。たとえば、

def return_tables(usertype)
  if (usertype=="Admin")
    @tables =.....(some way to retrieve the columns you want)
  else
  :
  end
end

そして、あなたはそれを呼び出すことができます:

return_tables(user.type)
于 2012-07-20T22:58:04.947 に答える