gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 08:29:06 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com