我有一个用户模型(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>
任何帮助高度赞赏。提前谢谢你
答案 0 :(得分:3)
我认为使用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 %>
希望它有所帮助。