has_many,through,source的Ruby on Rails关联返回NoMethodError

时间:2018-04-08 21:50:05

标签: ruby-on-rails

我有三个模型user.rbvote.rbevent.rb

用户

 has_many :votes, foreign_key: 'voter_id', dependent: :destroy
 has_many :voting, through: :votes, source: :voted

投票

  belongs_to :voter, class_name: "User"
  belongs_to :voted, class_name: "Event"

事件

  has_many :votes, foreign_key: 'voted_id', dependent: :destroy
  has_many :voters, through: :votes, source: :voter

出于某种原因,如果我致电User.first.voting,我会收到:NoMethodError: undefined method 'voted' for #<User:0x00007fbc56d069d8>

有人知道为什么吗?我已经搜索了关于这个主题的其他几个问题,我不知道我哪里出错了。

1 个答案:

答案 0 :(得分:0)

如果你在轨道5上,我做了一个有效的代码:

用户

  has_many :votes, foreign_key: 'voter_id', dependent: :destroy
  has_many :voting, through: :votes, source: :voted

事件

  has_many :votes, foreign_key: 'voted_id', dependent: :destroy
  has_many :voters, through: :votes, source: :voter

投票

  belongs_to :voter, class_name: "User", optional: true
  belongs_to :voted, class_name: "Event", optional: true

模式

  create_table "events", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "votes", force: :cascade do |t|
    t.integer "voter_id"
    t.integer "voted_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

测试(rails console)

> User.create
> Event.create
> Vote.create(:voter_id => 1, :voted_id => 1)
> User.first.voting
=> #<ActiveRecord::Associations::CollectionProxy
> User.first.voting.first # to get event instance
=> #<Event ...

希望这有帮助!