如何在 Rails 3 中引用没有模型的 HABTM 表中的数据?

发布于 2024-10-04 15:39:25 字数 2632 浏览 4 评论 0原文

因此,我最近在两个模型(项目和用户)之间创建了 HABTM 关系。

之前,我的项目表中有一个 user_id 列 - 其作用类似于外键。现在有一整张表可以做到这一点。

但是我如何引用具有特定 user_id & 的项目?项目ID?

例如,我的视图的一部分看起来像这样:

<div class="field">
        <%= f.label :project_id %><br />
        <%= collection_select(:stage, :project_id, Project.where(:user_id => current_user), :id, :name) %>
        <br />
    </div>

但是现在我如何从数据库中提取相同的信息,而没有 HABTM 表的模型?新表称为“projects_users”。

我的项目模型如下所示:

# == Schema Information
# Schema version: 20101125223049
#
# Table name: projects
#
#  id          :integer         not null, primary key
#  name        :string(255)
#  description :string(255)
#  notified    :boolean
#  created_at  :datetime
#  updated_at  :datetime
#

class Project < ActiveRecord::Base

  has_and_belongs_to_many :users
  has_many :stages, :dependent => :destroy
  has_many :uploads
  has_many :comments

  #before_validation { |project| project.user = Authorization.current_user unless project.user }

end

我的用户模型如下所示:

# == Schema Information
# Schema version: 20101124095341
#
# Table name: users
#
#  id                   :integer         not null, primary key
#  email                :string(255)     default(""), not null
#  encrypted_password   :string(128)     default(""), not null
#  password_salt        :string(255)     default(""), not null
#  reset_password_token :string(255)
#  remember_token       :string(255)
#  remember_created_at  :datetime
#  sign_in_count        :integer         default(0)
#  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)
#  role                 :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

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

顺便说一句...如何从 Rails 控制台编辑该表 - 没有模型?

谢谢。

So I recently created an HABTM relationship between two models (project & user).

Before, I had a user_id column in my project table - that would act like a foreign key. Now there is an entire table that does that.

But how do I reference projects that have a specific user_id & project_id ?

For instance, I used to have a section of my view that looked like this:

<div class="field">
        <%= f.label :project_id %><br />
        <%= collection_select(:stage, :project_id, Project.where(:user_id => current_user), :id, :name) %>
        <br />
    </div>

But how do I now pull the same info from the db, with no model for the HABTM table? The new table is called 'projects_users'.

My projects model looks like this:

# == Schema Information
# Schema version: 20101125223049
#
# Table name: projects
#
#  id          :integer         not null, primary key
#  name        :string(255)
#  description :string(255)
#  notified    :boolean
#  created_at  :datetime
#  updated_at  :datetime
#

class Project < ActiveRecord::Base

  has_and_belongs_to_many :users
  has_many :stages, :dependent => :destroy
  has_many :uploads
  has_many :comments

  #before_validation { |project| project.user = Authorization.current_user unless project.user }

end

My User Model looks like this:

# == Schema Information
# Schema version: 20101124095341
#
# Table name: users
#
#  id                   :integer         not null, primary key
#  email                :string(255)     default(""), not null
#  encrypted_password   :string(128)     default(""), not null
#  password_salt        :string(255)     default(""), not null
#  reset_password_token :string(255)
#  remember_token       :string(255)
#  remember_created_at  :datetime
#  sign_in_count        :integer         default(0)
#  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)
#  role                 :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

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

As an aside...how do I edit that table from the rails console - without a model?

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

韵柒 2024-10-11 15:39:25

我认为这对你有用。基本上,您会获取某个用户的所有项目,然后通过 project_id 缩小范围。

user_id = 3 #example
project_id = 2 #example
User.find(user_id).projects.find(project_id)

如果您想手动编辑连接表,可以直接使用关系。

project = Project.create
user = User.first

#add a new row to the join table for the user_id,project_id
user.projects << project 

#delete all records from the join table referencing this user.
user.projects = []  

I think this will work for you. Basically you're grabbing all the projects for a certain user and then narrowing it down by project_id.

user_id = 3 #example
project_id = 2 #example
User.find(user_id).projects.find(project_id)

If you want to manually edit the join table you can use the relationships directly.

project = Project.create
user = User.first

#add a new row to the join table for the user_id,project_id
user.projects << project 

#delete all records from the join table referencing this user.
user.projects = []  
╰つ倒转 2024-10-11 15:39:25

我不确定我完全理解你的问题,但是 Project.where(:user_id => current_user) 应该变成 current_user.projects

并将 id 1 的用户添加到你会做的 id 3 的项目

Project.find(3).users << User.find(1)

这是你一直在尝试做的吗?

I'm not sure I fully understand your question, but Project.where(:user_id => current_user) should become current_user.projects

And to add user with id 1 to project with id 3 you'd do

Project.find(3).users << User.find(1)

Is this what you've been trying to do ?

烏雲後面有陽光 2024-10-11 15:39:25

这个 RailsCasts 对我帮助很大 - 它将回答你的问题。 http://railscasts.com/episodes/163-self-referential-association

This RailsCasts helped me a lot - it will answer your questions. http://railscasts.com/episodes/163-self-referential-association

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文