私は最近、2つのモデル(プロジェクト&ユーザー)の間にHABTM関係を作成しました。Rails 3でモデルなしでHABTMテーブルのデータを参照するにはどうすればよいですか?
以前は、私のプロジェクトテーブルにuser_idカラムがありました。これは外部キーのように動作します。今、それを行うテーブル全体があります。
しかし、私は特定のuser_id & project_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テーブルの無いモデルとDBから同じ情報を、引っ張っていますか?新しいテーブルは '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
...どのように私は、レールコンソールからそのテーブルを編集する - なしモデル?
ありがとうございました。
がcurrent_user.projectsに変更されました。 Thnx。 2番目の部分については、それはコンソールでbになっていますか?そうであれば、動作しません。 – marcamillion
はい、コンソールで2番目の部分を使用する必要があります。それは動作するはずです。あなたは使用しているIDを持つインスタンスを持っていますか?代わりにこれを試してみてください:Project.first.users << User.first –
これはうまくいきました。どこでそれについてもっと読むことができますか?たとえば、コンソールからprojects_usersテーブルのすべてのエントリを表示するにはどうすればよいですか? – marcamillion