Как мне сделать одного пользователя «другим» в Rails 3? - PullRequest
1 голос
/ 11 января 2011

Итак, у меня уже есть базовые настройки.

Это моя модель пользователя:

# == Schema Information
# Schema version: 20110102225945
#
# Table name: users
#
#  id                   :integer         primary key
#  email                :string(255)
#  encrypted_password   :string(128)
#  password_salt        :string(255)
#  reset_password_token :string(255)
#  remember_token       :string(255)
#  remember_created_at  :datetime
#  sign_in_count        :integer
#  current_sign_in_at   :datetime
#  last_sign_in_at      :datetime
#  current_sign_in_ip   :string(255)
#  last_sign_in_ip      :string(255)
#  created_at           :datetime
#  updated_at           :datetime
#  username             :string(255)
#  f_name               :string(255)
#  l_name               :string(255)
#

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable, and :lockable
  devise :database_authenticatable, :registerable, :timeoutable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me

  has_and_belongs_to_many :projects
  has_many :stages
  has_many :uploads
  has_many :comments
  has_many :assignments
  has_many :roles, :through => :assignments
  has_and_belongs_to_many :owners,
                  :class_name => "User",
                  :association_foreign_key => "owner_id",
                  :join_table => "ownership"

  def role_symbols
    roles.map do |role|
      role.name.underscore.to_sym
    end
  end  
end

Моя ролевая модель выглядит так:

# == Schema Information
# Schema version: 20101117094659
#
# Table name: roles
#
#  id         :integer         not null, primary key
#  name       :string(255)
#  created_at :datetime
#  updated_at :datetime
#

class Role < ActiveRecord::Base
    has_many :assignments
    has_many :users, :through => :assignments
end

Назначение выглядиткак это:

# == Schema Information
# Schema version: 20101117094659
#
# Table name: assignments
#
#  id         :integer         not null, primary key
#  created_at :datetime
#  updated_at :datetime
#  user_id    :integer
#  role_id    :integer
#

class Assignment < ActiveRecord::Base
    belongs_to :role
    belongs_to :user
end

У меня есть таблица владения, которая имеет owner_id и user_id.

У меня есть одна запись в моей таблице, которая соответствует двум разным пользователям.Итак, мой вопрос: как мне взаимодействовать с пользователями / записями этого join_table.

Я хотел бы знать следующее:

  • Как мне взаимодействовать в моей консоли railsс данными в этой таблице собственности?Я пробовал owner.all, Owner.all, ownership.all, owners.all, но все безрезультатно.Итак, учитывая, что эта структура немного отличается от обычных ассоциаций, как мне это сделать?
  • В моем ERB, как мне перечислить всех «пользователей», которые связаны с current_user?Доступ к проектам, связанным с текущим пользователем, выглядит следующим образом: current_user.projects.each do |project|, тогда я могу сделать project.name и т. Д. Но не совсем уверен, как это сделать.

Спасибо

1 Ответ

3 голосов
/ 11 января 2011

Вот что сработало для меня (пример - отношение родитель / потомок, но концептуально оно такое же, как и у владельца / владельца)

# The corresponding table has a parent_id and a child_id columns
class Relation < ActiveRecord::Base
  belongs_to :parent, :class_name => “User”
  belongs_to :child, :class_name => “User”
end

class User < ActiveRecord::Base
  # The user’s parents
  # Get them from the relations where
  # the current user is a child
  has_many :parent_relations,
           :class_name => ‘Relation’,
           :foreign_key => ‘child_id’

  has_many :parents,
           :through => :parent_relations

  # The user’s children
  # Get them from the relations where
  # the current user is a parent
  has_many :children_relations,
           :class_name => ‘Relation’,
           :foreign_key => ‘parent_id’

  has_many :children,
           :through => :children_relations
end

В этом случае вы можете использовать следующее в ваших представлениях

- current_user.parents.each do |parent|
  %p= parent.email # Since the parent is a User

Надеюсь, это поможет

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...