I’m trying to write a conditional statement in my tasks controllers for a simple rails3 application.
Users have many tasks and tasks have one user.
When creating a task, we can chose who owns it:
<%= collection_select(:task, :user_id, User.all, :id, :name, {:prompt => true}) %>
I want the system to send an email to the owner of the task, only when it’s created for someone else. I.e. I do not need to receive an email when I create a task for myself.
My mailer’s working fine and in my tasks controller, I’ve tried this:
def create
@task = Task.new(params[:task])
respond_to do |format|
if @task.save and @task.user_id = current_user.id
format.html { redirect_to(tasks_path, :notice => 'Task was successfully created.') }
format.xml { render :xml => @task, :status => :created, :location => @task }
elsif @task.save
format.html { redirect_to(tasks_path, :notice => 'Task was successfully created.') }
format.xml { render :xml => @task, :status => :created, :location => @task }
TaskMailer.new_task(@task).deliver
else
format.html { render :action => "new" }
format.xml { render :xml => @task.errors, :status => :unprocessable_entity }
end
end
end
But it’s not really working… Any chance of some assistance.
Replace
@task.user_id = current_user.idwith@task.user_id == current_user.id.This is not the cause of your error, but you’re saving your task two times if
@task.user_id != current_user.id. You could do something like this instead: