NoMethodError: undefined method `user' for has_many :through Association

NoMethodError: undefined method `user' for has_many :through Association

我试图在我的 rails 应用程序中创建一个 has_many :through 关联,但是当我在 rails 控制台中执行以下操作时出现错误。

2.0.0-p481 :001 > @group = Group.first
Group Load (0.2ms)  SELECT "groups".* FROM "groups" ORDER BY "groups"."id" ASC LIMIT 1
=> #<Group id: 1, name: "First Group", description: "Woo", created_at: "2015-02-06 22:19:47", updated_at: "2015-02-06 22:19:47"> 
2.0.0-p481 :002 > @group.user

NoMethodError: undefined method `user' for #<Group:0x00000004d53eb0>
from /home/jon/.rvm/gems/ruby-2.0.0-p481/gems/activemodel-4.0.2/lib/active_model/attribute_methods.rb:439:in `method_missing'
from /home/jon/.rvm/gems/ruby-2.0.0-p481/gems/activerecord-4.0.2/lib/active_record/attribute_methods.rb:155:in `method_missing'
from (irb):2
from /home/jon/.rvm/gems/ruby-2.0.0-p481/gems/railties-4.0.2/lib/rails/commands/console.rb:90:in `start'
from /home/jon/.rvm/gems/ruby-2.0.0-p481/gems/railties-4.0.2/lib/rails/commands/console.rb:9:in `start'
from /home/jon/.rvm/gems/ruby-2.0.0-p481/gems/railties-4.0.2/lib/rails/commands.rb:62:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'

我的模特:

用户:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  before_create :do_mailchimp

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :memberships
  has_many :groups, through: :memberships


  def do_mailchimp
      gb = Gibbon::API.new("API")
      gb.lists.subscribe({:id => 'ID', 
       :email => {:email => self.email },:double_optin => false})
  end

end

群组:

class Group < ActiveRecord::Base

    has_many :memberships
    has_many :users, through: :memberships

end

会员资格:

class Membership < ActiveRecord::Base

    belongs_to :user
    belongs_to :group

end

我的迁移:

设计创建用户:

class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table(:users) do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at


      t.timestamps
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end

创建群组:

class CreateGroups < ActiveRecord::Migration
  def change
    create_table :groups do |t|
      t.string :name
      t.string :description

      t.timestamps
    end
  end
end

创建会员资格:

class CreateMemberships < ActiveRecord::Migration
  def change
    create_table :memberships do |t|

      t.timestamps
    end
  end
end

AddUserAndGroupIdToMemberships:

class AddUserAndGroupIdToMemberships < ActiveRecord::Migration
  def change
    add_column :memberships, :user_id, :integer
    add_index :memberships, :user_id
    add_column :memberships, :group_id, :integer
    add_index :memberships, :group_id
  end
end

我的架构:

ActiveRecord::Schema.define(version: 20150206225251) do

  create_table "groups", force: true do |t|
    t.string   "name"
    t.string   "description"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "memberships", force: true do |t|
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id"
    t.integer  "group_id"
  end

  add_index "memberships", ["group_id"], name: "index_memberships_on_group_id"
  add_index "memberships", ["user_id"], name: "index_memberships_on_user_id"

  create_table "users", force: true do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end

感谢您抽出宝贵时间希望您能提供帮助。

您定义了一个Group has_many :users。因此,一个组没有 user 方法,但有 users 方法:

@group = Group.first

@group.users          #=> returns an array with all users in the first group
@group.users.first    #=> returns the first user in the first group