我的 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
我希望能够更新用户模型的关联服务,而无需指定密码和密码确认属性。我怎样才能做到这一点?
最佳答案
两个选项...
如果您有简单的逻辑,例如仅在创建用户时验证密码,那么这将起作用:
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
关于ruby-on-rails - 如何更新 RoR 模型的关联而不更新相应模型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5638993/