【问题标题】:Accessing the attributes of a has many association in Rails在 Rails 中访问 a 的属性有很多关联
【发布时间】: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

它为&lt;ActiveRecord::Associations::CollectionProxy&gt;返回一个无方法错误

高度赞赏任何帮助。提前谢谢你

【问题讨论】:

  • 究竟返回了什么错误?什么方法不存在?请分享错误消息和完整的堆栈跟踪。
  • 它说@bu_factors 没有方法“zero_till_one”。同样,当我在控制台中使用 user_id 创建一个 Bu Factor 实例并从用户实例访问它时,我得到了同样的错误。
  • 当你调试@bu_factors时你看到了什么
  • #<:associations::collectionproxy>]>
  • @SebastianPeter 您只选择了最后一行,删除订单后不需要order,然后尝试看看会发生什么

标签: ruby-on-rails ruby


【解决方案1】:

我认为使用params[:id] 返回的用户没有任何与之相关的bu_factors,因为您的关系还可以。

我认为你需要在控制器中尝试这样的事情:

if @user.bu_factors.count >= 1
   @bu_factors = @user.bu_factors.last
else
   @bu_factors = []
end

或者根据答案评论更容易

@bu_factors = @user.bu_factors.last || []

在视图中:

<% if @bu_factors.present? %>
    <%= @bu_factors.zero_till_one %>
<% else %>
    <%= "You have none any Bu Factor" %>
<% end %>

希望对你有帮助。

【讨论】:

  • 可以将控制器中的5行条件语句替换为@bu_factors = @user.bu_factors.last || []
  • @moveson 没错,这更容易理解
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-21
  • 1970-01-01
  • 2016-05-21
  • 1970-01-01
相关资源
最近更新 更多