[英]Couple of Rails issues that i didn't understand
我只是通过本教程学习Rails,有些事情我不明白:
1-这两个作业之间有什么区别? 为什么我可以在同一个助手中使用它?
def current_employee=(employee)
@current_employee = employee
end
def current_employee
remember_token = Employee.hash(cookies[:remember_token])
@current_employee ||= Employee.find_by(remember_token: remember_token)
end
2-这两个更新功能之间有什么区别,为什么这里需要json?
def update
respond_to do |format|
if @employee.update(employee_params)
format.html { redirect_to @employee, success: 'Employee was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @employee.errors, failure: :unprocessable_entity }
end
end
end
和
def update
@employee = Employee.find(params[:id])
if @employee.update_attributes(employee_params)
# Handle a successful update.
else
render 'edit'
end
end
1-这两个作业之间有什么区别? 为什么我可以在同一个助手中使用它?
def current_employee=(employee)
@current_employee = employee
end
def current_employee
remember_token = Employee.hash(cookies[:remember_token])
@current_employee ||= Employee.find_by(remember_token: remember_token)
end
第一个称为current_employee=(employee)
,称为setter
,因为您在@current_employee
上设置了新值。 第二个称为current_employee
,称为getter
,因为您可以获取@current_employee
的当前值。 有关setter和getter的更多信息 。
在getter方法中, ||=
用于memoization
。 因此,第一次调用current_employee
, Employee.find_by(remember_token: remember_token)
@current_employee
Employee.find_by(remember_token: remember_token)
值将分配给@current_employee
。 在随后的对getter方法的调用中,将检索相同的值。
2-这两个更新功能之间有什么区别,为什么这里需要json?
def update
respond_to do |format|
if @employee.update(employee_params)
format.html { redirect_to @employee, success: 'Employee was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @employee.errors, failure: :unprocessable_entity }
end
end
end
和
def update
@employee = Employee.find(params[:id])
if @employee.update_attributes(employee_params)
# Handle a successful update.
else
render 'edit'
end
end
两种update
方法本质上是相同的。 最后一个仅响应HTML格式。 第一个示例同时响应HTML和JSON格式。 如果您不需要响应JSON格式,则可以保留最后一个格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.