Steve Wright
Steve Wright

Reputation: 2511

Conditional value for ActiveRecord create method only

I have a form where I have an administrator creating new users. The form uses the User model I created (login, password, first_name, etc...). For the last field on the form, I want to have a checkbox that doesn't need to be stored as part of the User record, but it is needed for the controller. This will control if the newly created user will receive a welcome email or not. This is in Rails 3.0.3.

def create
  @user = User.new(params[:user])

  if @user.save
    if @user.send_welcome_email
      UserMailer.welcome_email(@user).deliver
    end
    redirect_to(admin_users_url, :notice => "User #{@user.name} was successfully created.")
  else
    render :action => "new"
  end
end

In my view (haml) I am trying to access it like this:

  %p
    Send Welcome Email?
    = f.check_box :send_welcome_email

I tried to make this an attr_accessible: :send_welcome_email but the controller does not recognize it. I get an

undefined method 'send_welcome_email' for #<User:0x00000100d080a8>;

I would like it to look like this:

What is the best way to get this working?

Upvotes: 1

Views: 257

Answers (3)

vonconrad
vonconrad

Reputation: 25377

As an alternative to attr_accessor, you can always remove it from the parameters first:

def create
  send_welcome_email = params[:user].delete(:send_welcome_email)
  @user = User.new(params[:user])

  if @user.save
    UserMailer.welcome_email(@user).deliver if send_welcome_email
    redirect_to(admin_users_url, :notice => "User #{@user.name} was successfully created.")
  else
    render :action => "new"
  end
end

You may have to make sure that the parameter is successfully transformed into a boolean; otherwise the condition will always be true (0 is true in Ruby).

Upvotes: 0

Brian Deterling
Brian Deterling

Reputation: 13734

Since you're not saving it on the user, you can use check_box_tag instead of f.check_box and access it with params[:send_welcome_email]. Although even the way you have it, I think you could access it as params[:user][:send_welcome_email].

Upvotes: 0

glebm
glebm

Reputation: 21100

What you want is not attr_accessible, but attr_accessor. That's it.

However, your code will look nicer if you move the email sending code to an observer.

Upvotes: 2

Related Questions