[英]Rails3 Conditional Statements in Controller Actions
我正在嘗試在我的任務控制器中為簡單的rails3應用程序編寫一個條件語句。
用戶有許多任務,任務有一個用戶。
創建任務時,我們可以選擇誰擁有它:
<%= collection_select(:task, :user_id, User.all, :id, :name, {:prompt => true}) %>
我希望系統只有在為其他人創建電子郵件時才向該任務的所有者發送電子郵件。 即,當我為自己創建任務時,我不需要收到電子郵件。
我的郵件工作正常,在我的任務控制器中,我試過這個:
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
但它並沒有真正起作用......有任何幫助的機會。
用@task.user_id == current_user.id
替換@task.user_id = current_user.id
@task.user_id == current_user.id
。
這不是導致錯誤的原因,但是如果@task.user_id != current_user.id
將任務保存兩次。 你可以這樣做:
def create
@task = Task.new(params[:task])
respond_to do |format|
if @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 if @task.user_id != current_user.id
else
format.html { render :action => "new" }
format.xml { render :xml => @task.errors, :status => :unprocessable_entity }
end
end
end
end
你沒有存儲創作者的身份證明嗎? 如果這樣做,您需要的所有數據都在模型中。 因此,只需在Task模型中實現私有實例方法。 像下面這樣的東西
# Task model
private
def notify_assignee
if new_record? || user_id_changed? && creator_id != user_id
TaskMailer.new_task(@task).deliver
end
end
調用上面的方法after_save
# Task model
after_save :notify_assignee
如果您未將creator_id存儲在數據庫中,請創建名為:creator_id
的屬性:creator_id
。
# Task model
attr_accessor :creator_id
在控制器中,在保存之前,執行
# Tasks controller
@task.creator_id = current_user.id
而上述方法仍然有效。
您的控制器重新指示將自動簡化為
if @task.save
format.html { redirect_to(tasks_path, :notice => 'Task was successfully created.') }
format.xml { render :xml => @task, :status => :created, :location => @task }
else
format.html { render :action => "new" }
format.xml { render :xml => @task.errors, :status => :unprocessable_entity }
end
而且這也是正確的方式,因為“業務邏輯”(在您的情況下是向受讓人發送電子郵件,通知其他人已經為其分配了任務 )將駐留在模型中。
這是因為這一行,你使用的是賦值=
而不是比較==
此外,current_user應該是@current_user
因為您沒有在方法中指定它。 (或者你有一個你沒有發布的方法current_user()
。那很好)
if @task.save and @task.user_id = current_user.id
它應該是
if @task.save and @task.user_id == @current_user.id
你應該將郵件內容移動到Task
-model並使用after_save
-callback。
也許您需要更改此行: @task.user_id = current_user.id
to @task.user_id == current_user.id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.