【发布时间】:2015-03-20 18:04:49
【问题描述】:
我正在使用 rails 4 中的一个项目,其中用户可以拥有多个项目,并且许多人与一个项目相关联。 IE。项目和用户共享多对多关系。
我使用这个迁移代码创建了一个新表 -
class CreateProjectsUsersJoin < ActiveRecord::Migration
def change
create_table :projects_users_joins, :id => false do |t|
t.integer :user_id
t.integer :project_id
end
add_index :projects_users_joins, ["user_id","project_id"]
end
end
并通过以下方式添加关联 -
class Project < ActiveRecord::Base
validates :name , :presence => true
validates :description, :presence => true
#associations
has_and_belongs_to_many :users
end
class User < ActiveRecord::Base
include CarrierWave::MiniMagick
#removes the white spaces before validating the data
before_validation :strip_whitespace, :only => [:name,:email]
#data validations
validates :email, :presence =>true, :uniqueness => {case_sensitive: false}, :format => { :with=> /([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/, :message => "please enter a valid e-mail" }
validates :name, :presence=>true
validates :password ,:presence =>true, :confirmation=> true #, :length =>{ :minimum=>6, :maximum=>30}, :format=>{:with=>/(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,30}/}
#for the image
mount_uploader :image, ImageUploader
#for the password
has_secure_password
#associations
has_many :issues
has_many :comments
has_and_belongs_to_many :projects
end
#squishes the data(removes heading and trailing white spaces and replaces multiple space by songle)
def strip_whitespace
self.email = self.email.squish
self.name = self.name.squish
end
当我在 rails 控制台上运行以下命令时,我得到一个无方法错误 - 请帮忙
pro = Project.find(1) (works)
me = User.find(27) (works)
pro.users << me (throws a no method defined error)
请帮忙
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 has-and-belongs-to-many