【问题标题】:No method error没有方法错误
【发布时间】: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


    【解决方案1】:

    您输入了错误的表名。 As the docs say 默认连接表名应该只是两个类的复数名称,按词法顺序用下划线连接。所以projects_users 在这种情况下。

    如果您想要projects_users_joins,那么您可以在两个habtm 调用中提供:join_table 选项,或者(我的建议)执行该迁移的rake db:migrate:down,然后删除"_joins" 并再次迁移设置默认表名。

    【讨论】:

      猜你喜欢
      • 2018-04-05
      • 2023-03-29
      • 2012-11-09
      • 1970-01-01
      • 1970-01-01
      • 2011-08-21
      • 2011-02-08
      • 2012-10-07
      • 1970-01-01
      相关资源
      最近更新 更多