代码之家  ›  专栏  ›  技术社区  ›  Paul

部分更新Rails 3中的模型

  •  0
  • Paul  · 技术社区  · 16 年前

    我有一个rails模型:

    class User < ActiveRecord::Base
    
      attr_accessor :password
      attr_accessible :name, :email, :password, :password_confirmation, :description 
    
      email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    
      validates :email,    :presence => true
    
      validates :name,     :presence => true
    
      validates :password, :presence => true
    
      ...
    
    end
    

    在我的控制器中,我有以下更新方法:

    def update
      @user = User.find(params[:id])
    
      respond_to do |format|
        if @user.update_attributes(:name => params[:name], :email => params[:email])
          flash[:success] = "Profile updated"
          format.html { redirect_to(@user, :notice => 'User was successfully updated.') }
          format.xml  { head :ok }
        else
          @title = "Edit user"
          format.html { render :action => "edit" }
          format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
        end
      end
    end
    

    这将失败,并显示一条奇怪的错误消息:

    undefined method `downcase' for nil:NilClass
    

    2 回复  |  直到 13 年前
        1
  •  2
  •   tadman    16 年前

    如果插入某种帮助器方法,则可以有条件地触发验证。这通常是多阶段条目或部分更新的情况:

    class User < ActiveRecord::Base
      validates :password,
        :presence => { :if => :password_required? }
    
    protected
      def password_required?
        self.new_record?
      end
    end
    

    password 和 password_confirmation 是暂时的 attr_accessor 以后散列和保存的方法。

        2
  •  1
  •   Simone Carletti    16 年前

    下面这行是错的

    @user.update_attributes(params[:name], :email => params[:email])
    

    更新属性需要哈希。

    @user.update_attributes(:name => params[:name], :email => params[:email])
    

    另外,你应该使用 form_for params[:user] 搞砸。