繁体   English   中英

has_many的Ruby on Rails关联通过源返回NoMethodError

[英]Ruby on Rails associations for has_many, through, source returns NoMethodError

我有3个模型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>

有人知道为什么吗? 我在Google上搜索了有关此主题的其他一些问题,但看不到哪里出了问题。

如果您在轨道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控制台)

> 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 ...

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM