2

我正在尝试检查-是否更改了某些(语言)属性,并且是否等于某个值,我需要将其更改为其他适当的值。

这是我的代码:

编辑

    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

我的表格:

  <%= 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"]) %>

当我更改类别时 - 它会将语言更改为默认值。我怎样才能防止这种情况?

给我错误:

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

我做错了什么?

4

2 回答 2

5

我刚刚通过控制台尝试了这个,看起来 ActiveRecord 没有在你进行大规模属性更新时跟踪更改,例如@website.attributes = params[:website]. 做类似的事情可能更简单if @website.language != params[:website][:language](当然,稍后将更新移动到某个地方。)。有点丑,我意识到,但它会工作。当然,您始终可以考虑增强您的模型以跟踪大规模更新的变化。

关于更改字段 - 听起来您的选择列表未初始化为正确的值。如果 的值为@website.category“foo”,则当此页面加载时,选择列表应选择“foo”。这似乎没有发生,因此当您提交表单并进行质量属性更新时,它会将类别属性更新为默认选择的任何列表项。

于 2012-10-04T14:49:17.900 回答
0

@website.language_changed?是方法,你可以看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
于 2012-10-04T14:17:26.830 回答