Rails 4 has_many:通过访问连接表上的字段

时间:2015-06-26 09:26:00

标签: ruby-on-rails-4 has-many-through

我有3个型号:

class User < ActiveRecord::Base
  has_many :user_leave_portfolios
  has_many :leave_portfolios, :through => :user_leave_portfolios
end

class LeavePortfolio < ActiveRecord::Base
  has_many :user_leave_portfolios, dependent: :destroy
  has_many :users, :through => :user_leave_portfolios
end

class UserLeavePortfolio < ActiveRecord::Base
  belongs_to :user
  belongs_to :leave_portfolio

  # this table has an additional field named 'leave_amount'
end

&#39; leave_amount&#39; user_leave_portfolio表中的字段用作基于leave_portfolio的用户选择的休假金额

根据文档和其他各种博客和文章,我应该可以访问“离开金额”和#39;字段:

u = User.first
u.leave_portfolios.first.leave_amount

但是,我收到以下错误:

  

NoMethodError:未定义的方法`leave_amount&#39; for #LeavePortfolio:0x007f8708e3dbe0

架构:

create_table "leave_portfolios", force: :cascade do |t|
  t.string   "name",             limit: 255
  t.integer  "calculation_type", limit: 4
  t.integer  "period",           limit: 4
  t.integer  "default_amount",   limit: 4
  t.integer  "organisation_id",  limit: 4
  t.datetime "created_at",                   null: false
  t.datetime "updated_at",                   null: false
end

create_table "user_leave_portfolios", force: :cascade do |t|
  t.integer  "leave_portfolio_id", limit: 4
  t.integer  "user_id",            limit: 4
  t.float    "leave_amount",       limit: 24
  t.datetime "created_at",                    null: false
  t.datetime "updated_at",                    null: false
end

create_table "users", force: :cascade do |t|
  t.string   "email",                  limit: 255, default: "", null: false
  t.string   "encrypted_password",
  .
  .
  .
end

1 个答案:

答案 0 :(得分:1)

你应该做

u = User.first
u.user_leave_portfolios.first.leave_amount

leave_amount中的user_leave_portfolios不在leave_portfolios。{/ p>