CodeBoy CodeBoy -4 years ago 98
Ruby Question

model which belongs to User, unable to access user_id

I have an app in which week objects may be approved or rejected, this is done in the week controller. My week model belongs_to user. Here is a short example of what I'm doing in the week controller:

The first block is provided for some context:

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)


Below is the rejection half:

elsif params[:commit] == "Reject selected weeks"
user_week = Week.where(id: params[:weeks_ids])
user_week.update_all(approved?: false)


Above, the weeks are updated perfectly. Below, I try to retrieve a user from the selected week so that I can send an email to that user.

#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


When I try to reject a week however, I receive the following error:

undefined method `user_id' for <Week::ActiveRecord_Relation:0x007fdcac43e730>


Is this due to an unspecified User object?

Answer Source

Week::ActiveRecord_Relation is a set of records, not just a single one... it's like calling user_id on an array, which won't quite work the way you want.

What you want is to call user_id on a single instance of Week To do that you can either:

a) fetch out a single week (probably not what you want)

b) run each on the Active Relation eg:

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) fetch the set of user_emails by converting the user_weeks to user_ids (but then iterate over the emails) eg:

# 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) assume that it's always for the same user anyway and just use the first week eg:

  #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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download