我有一个应用程序,其中周对象可能被批准或拒绝,这是在周控制器中完成的。我的周模型belongs_to用户。以下是我在周控制器中所做的一个简短示例:
第一个块是为某些上下文提供的:
def approve
@user = current_user
if params[:commit] == "Approve selected weeks"
Week.where(id: params[:weeks_ids]).update_all(approved?: true)
flash[:success] = "Selected weeks were approved!"
#Send an email noting it was approved
@user.send_approved(current_user)
以下是拒绝一半:
elsif params[:commit] == "Reject selected weeks"
user_week = Week.where(id: params[:weeks_ids])
user_week.update_all(approved?: false)
以上,这几周完美更新。下面,我尝试从所选周中检索用户,以便我可以向该用户发送电子邮件。
#get the user associated with the rejected week, send them an email.
user_email = User.find(id: user_week.user_id)
UserMailer.send_rejection(user_email).deliver
flash[:info] = "Selected weeks were Rejected."
end
redirect_to weeks_path
end
但是当我尝试拒绝一周时,我收到以下错误:
undefined method `user_id' for <Week::ActiveRecord_Relation:0x007fdcac43e730>
这是由于未指定的用户对象吗?
答案 0 :(得分:1)
Week::ActiveRecord_Relation
是记录的集,不仅仅是一个记录......它就像在数组上调用user_id
一样,赢得了#{1}}。以你想要的方式工作。
您想要的是在user_id
的单个实例上致电Week
要做到这一点,你可以:
a)取出一周(可能不是你想要的)
b)在活动关系上运行each
,例如:
user_weeks.each do |user_week|
#get the user associated with the rejected week, send them an email.
user_email = User.find(user_week.user_id)
UserMailer.send_rejection(user_email).deliver
end
c)通过将user_weeks转换为user_ids(但随后迭代电子邮件)来获取user_emails集合,例如:
# get the user associated with the rejected week, send them an email.
users = User.find(user_weeks.pluck(:user_id))
users.each do |user|
UserMailer.send_rejection(user).deliver
end
d)假设它总是为同一个用户而且只使用第一周,例如:
#get the user associated with the rejected week, send them an email.
user_email = User.find(user_week.first.user_id)
UserMailer.send_rejection(user_email).deliver
答案 1 :(得分:1)
user_week
似乎是一周的集合,而不是一周。
您可能正在寻找的是发送多封拒绝电子邮件。您可以在user_weeks
中循环所有周,并通过执行以下操作发送多封电子邮件:
elsif params[:commit] == "Reject selected weeks"
user_weeks = Week.where(id: params[:weeks_ids])
user_weeks.update_all(approved?: false)
user_weeks.each do |w|
user_email = User.find(id: w.user_id)
UserMailer.send_rejection(user_email).deliver
end
flash[:info] = "Selected weeks were Rejected."
end
redirect_to weeks_path
end