ruby-on-rails - 如何更新 RoR 模型的关联而不更新相应模型的属性

标签 ruby-on-rails ruby rails-activerecord

我的 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/

相关文章:

ruby-on-rails - 在Rails Controller 中使用清理

ruby-on-rails - 如何打印 FactoryGirl.create 进行的 Model.create 调用?

ruby-on-rails - has_many:通过查询两个值

ruby-on-rails - 验证时 Mechanize 405 错误

ruby-on-rails - Current_user && 用户个人资料

javascript - 如何在 Rails 中将拖放项目的顺序保存到数据库中?

sql - 循环 SQL 结果集的更好方法

ruby-on-rails - 运行 db :seed 时数组的未定义方法 'transactions'

ruby-on-rails - 解析 'Gemfile'时出错

ruby-on-rails - 在 Windows 上启动 Rails 服务器时出错