如何在不更新相应模型属性的情况下更新RoR模型的关联

时间:2011-04-12 17:07:25

标签: 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

我希望能够更新用户模型的关联服务,而无需指定密码和密码确认属性。我怎么能这样做?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

答案 2 :(得分:0)

您需要查看条件验证,以指定在更新/保存模型时是否应验证模型中的密码属性。这是Railscast一集,虽然有点过时,但仍然相当简单,应该让你走上正确的道路