2011-04-12 59 views
2

我有以下車型(含相應的數據庫表)在我的Rails 3應用程序:如何更新回報率模型協會,而不更新相應的模型的屬性

class User < ActiveRecord::Base 
    has_many :service_users 
    has_many :services, :through => :service_users 

    attr_accessor :password 

    attr_accessible :password, :password_confirmation, :service_ids 

    validates :password, :presence => true, 
         :confirmation => true, 
         :length => { :within => 6..40 } 
    ... 
end 

class Service < ActiveRecord::Base 
    has_many :service_users 
    has_many :users, :through => :service_users 
    ... 
end 


class ServiceUser < ActiveRecord::Base 
    belongs_to :service 
    belongs_to :user 
end 

#User Controller: 

class UsersController < ApplicationController 
    ... 
    def update 
    @user = User.find(params[:id]) 
    if @user.update_attributes(params[:user]) 
     flash[:success] = "Profile updated." 
     redirect_to @user 
    else 
     @title = "Edit user" 
     render 'edit' 
    end 
    end 
    ... 
end 

我希望能夠更新用戶模型而不必指定密碼和密碼確認屬性。我怎樣才能做到這一點?

回答

4

兩個選項...

如果你有簡單的邏輯,像只驗證創建用戶時的密碼,這將工作:

validates :password, :presence => true, 
        :confirmation => true, 
        :length => { :within => 6..40 }, 
        :if => :new_record? 

更可能的是,您需要一個組合以便用戶更新密碼:

validates :password, :presence => true, 
        :confirmation => true, 
        :length => { :within => 6..40 }, 
        :if => :is_password_validation_needed? 

# Protect the password attribute from writing an 
# empty or nil value 
def password=(pass) 
    return if !pass.present? 
    @password = pass 
end 

private 

    def is_password_validation_needed? 
    # Return true if the record is unsaved or there 
    # is a non-nil value in self.password 
    new_record? || password 
    end 
+0

這是在路上,但只是建議,如果你使用這種情況下,你真的想讓你的用戶更改他們的密碼,如果無法以某種方式蔓延到該等式,那麼將不會啓動驗證以防止無保存與模型。這怎麼會發生誰知道,但我認爲設置一個attr_accessor在railscasts中概述是一個更安全的賭注 – 2011-04-12 19:49:10

+0

嗯,現在我的密碼設置爲空白。也許這是因爲我使用params [:user]調用update_attributes,因爲它沒有設置,所以它使用空白密碼字段重寫密碼屬性。我如何只用我想更新的屬性來調用update_attribute(s)? 'def update @user = User.find(params [:id]) if @ user.update_attributes(params [:user]) flash [:success] =「配置文件已更新。」 redirect_to的@user 否則 @title = 「編輯用戶」 渲染 '編輯' 結束 end' – sizzle 2011-04-12 20:32:20

+0

我會建議密碼setter函數。我會用我的建議更新答案。數據庫中沒有「密碼」列,對(這會很糟糕)? Authlogic gem是獲得一些見解的好地方:https://github.com/binarylogic/authlogic/blob/master/lib/authlogic/acts_as_authentic/password.rb#L235 – tihm 2011-04-12 20:50:24

0

您將希望查看條件驗證以指定在更新/保存模型時是否驗證模型中的密碼屬性。這裏是一個Railscast插曲,雖然有點過時,仍然是相當簡單,應該讓你離正確的道路上