【发布时间】:2018-01-27 10:32:31
【问题描述】:
我有一个用户模型(user.rb):
class User < ApplicationRecord
has_many :bu_factors, dependent: :destroy
attr_accessor :remember_token, :activation_token, :reset_token
before_save :downcase_email
before_create :create_activation_digest
....
end
与 bu_factor 模型具有 has_many 关系,该模型与用户模型具有belongs_to 关系:
class BuFactor < ApplicationRecord
belongs_to :user
default_scope -> { order(created_at: :asc)}
validates :user_id, presence: true
validates :zero_till_one, :one_till_two, :two_till_three, :three_till_four, :four_till_five, :five_till_six, :six_till_seven, :seven_till_eight, :eight_till_nine, :nine_till_ten, :ten_till_eleven, :eleven_till_twelve, :twelve_till_thirteen, :thirteen_till_fourteen, :fourteen_till_fifteen, :fifteen_till_sixteen, :sixteen_till_seventeen, :seventeen_till_eightteen, :eightteen_till_nineteen, :nineteen_till_twenty, :twenty_till_twentyone, :twentyone_till_twentytwo, :twentytwo_till_twentythree, :twentythree_till_zero, presence: true, numericality: :true
end
在 users_controller 我有一个 edit_settings 操作,我需要访问属于当前用户的最后创建的 bu_factor,以便在视图中我可以显示单个属性
<%= @bu_factors.zero_till_one %>
等等
我怎样才能做到这一点?我的控制器操作不起作用:
def edit_settings
#should return the latest created bu_factors for the current user
@user = User.find(params[:id])
@bu_factors = @user.bu_factors.order('created_at').last
end
它为<ActiveRecord::Associations::CollectionProxy>返回一个无方法错误
高度赞赏任何帮助。提前谢谢你
【问题讨论】:
-
究竟返回了什么错误?什么方法不存在?请分享错误消息和完整的堆栈跟踪。
-
它说@bu_factors 没有方法“zero_till_one”。同样,当我在控制台中使用 user_id 创建一个 Bu Factor 实例并从用户实例访问它时,我得到了同样的错误。
-
当你调试
@bu_factors时你看到了什么 -
#<:associations::collectionproxy>]>
-
@SebastianPeter 您只选择了最后一行,删除订单后不需要
order,然后尝试看看会发生什么
标签: ruby-on-rails ruby