MID
MID

Reputation: 1825

How to change object attribute in update action?

I need to use method, which is working only in controller, but I can't implement changing attribute.

Here is my update action:

def update
@website = Website.find(params[:id])
respond_to do |format|
 if @website.update_attributes(params[:website]) 
  if params[:website][:language] == "Auto"
    @website.[:website][:language] =  full_language("request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first")
  end

    format.html { redirect_to @website, notice: 'website was successfully updated.' }
    format.js
  else
    format.html { render action: "edit" }
    format.js { render action: "edit" }
  end
end

end

What I'm doing wrong ?

Upvotes: 0

Views: 807

Answers (2)

Denis Tataurov
Denis Tataurov

Reputation: 193

def update
  @website = Website.find(params[:id])
  if params[:website][:language] == "Auto"
    params[:website][:language] = full_language("request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first")
  respond_to do |format|
  if @website.update_attributes(params[:website]) 
    format.html { redirect_to @website, notice: 'website was successfully updated.' }
    format.js
  else
    format.html { render action: "edit" }
    format.js { render action: "edit" }
  end
end

end

Upvotes: 0

Simone Carletti
Simone Carletti

Reputation: 176352

@website.update_attributes(params[:website])

already performs the save to the database.

@website.[:website][:language] =  full_language("request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first")

doesn't make any sense.

@website.language = full_language(request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first)

does. Also note the removal of quotes before request.env. Beware that you need to save again the changes, so it makes sense to move everything before the update attributes and use one single save call.

def update
  @website = Website.find(params[:id])
  @website.attributes = params[:website]

  if params[:website][:language] == "Auto"
    @website.language = full_language(request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first)
  end

  respond_to do |format|
   if @website.save
    format.html { redirect_to @website, notice: 'website was successfully updated.' }
    format.js
  else
    format.html { render action: "edit" }
    format.js { render action: "edit" }
  end
end

Last but not least, you might want to stop for a second and learn a little bit of Ruby syntax and ActiveRecord, before proceeding to the next coding session.

Upvotes: 1

Related Questions