Reputation:
I'm just learning rails with this tutorial and there are couple of things i can't understand:
1- whats the difference between these two assignments? why can i use it in the same helper?
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- what's the difference between these 2 update functions, and why the json needed here?
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
and
def update
@employee = Employee.find(params[:id])
if @employee.update_attributes(employee_params)
# Handle a successful update.
else
render 'edit'
end
end
Upvotes: 0
Views: 75
Reputation: 2353
1- whats the difference between these two assignments? why can i use it in the same helper?
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
The first one, current_employee=(employee)
, is called a setter
, because you set a new value on @current_employee
. The second one, current_employee
, is called getter
, because you get the current value of the @current_employee
. More info about setters and getters.
In the getter method, the ||=
is used for memoization
. So the first time you call current_employee
the value of Employee.find_by(remember_token: remember_token)
is assigned to @current_employee
. In subsequent calls to the getter method, you retrieve the same value.
2- what's the difference between these 2 update functions, and why the json needed here?
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
and
def update
@employee = Employee.find(params[:id])
if @employee.update_attributes(employee_params)
# Handle a successful update.
else
render 'edit'
end
end
Both update
methods are esentially the same. The last one is responding only to HTML format. The first example is responding to both, HTML and JSON formats. If you don't need to response to JSON format, you can stay with the last one.
Upvotes: 4