Question

I'm trying to check - if some (language) attribute is changed and if it is equal to some value I need to change it into other proper value.

Here is my code:

EDIT:

    def update
@website = Website.find(params[:id])
@website.language = params[:website][:language]
if @website.language_changed?
  if params[:website][:language] == "Automatic (by user's browser language)"
    @website.language = full_language(request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first)
  end
end
respond_to do |format|
 if @website.save
   format.html { redirect_to @website, 
  notice: 'Note: code has been updated. Please replace the code you have on your website with the code below. Only then changes will take effect.' }
   end
  end
end

My form:

  <%= f.label "Website category"%>
  <%= f.select :category, options_for_select([
      "--- please select ---",
      "Banking",
      "Computers]) %>
  <%= f.label "Language preferences"%>
  <%= f.select :language, options_for_select([
       "--- please select ---",  
       "Automatic (by user's browser language)",
        "Arabic",
        "Chinese"]) %>

And when I'm changing category - it changint language to default. How can I prevent this ?

Gives me error:

   undefined method `updated?' for "--- please select ---":String

What I'm doing wrong ?

Was it helpful?

Solution

I just tried this via the console, and it looks like ActiveRecord isn't tracking the change when you do a mass attribute update like @website.attributes = params[:website]. It may be simpler to just do something like if @website.language != params[:website][:language] (and move your update somewhere later, of course.). A little uglier, I realize, but it would work. Of course, you can always look at enhancing your model to track changes from mass updates.

Regarding the fields changing - it sounds like your select list is not initializing to the correct values. If the value of @website.category is "foo", then when this page loads the select list should have "foo" selected. That doesn't seem to be happening, so when you submit the form and do your mass attribute update, its updating the category attribute to whatever list item was selected by default.

OTHER TIPS

@website.language_changed? is method,you can watch http://railscasts.com/episodes/109-tracking-attribute-changes

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

  if params[:website][:language] == "Automatic (by user's browser language)" &&  @website.language != params[:website][:language]
    params[:website][:language] = full_language(request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first)
  end
  if @website.update_attributes(params[:website])
  end

end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top