繁体   English   中英

Rails从OrdersController更新用户模型的属性

[英]Rails updating attributes of a User Model from OrdersController

这是我的代码:

class OrdersController

def create
  @order = Order.new(params[:order])
    if @order.purchase
      work = GATEWAY.store(credit_card, options)
      result = work.params['billingid']
      current_user.update_attributes(:billing_id => result)
    end
  end
end

billingid通过运行返回GATEWAY.store(credit_card, options)我试图拯救这个返回billingid:billing_id列在用户模型。 是否无法从不是UsersController的用户模型更新属性?

简单地说,是否无法从模型#2的控制器更新模型#1的属性?

谢谢

更新:在下面的人的帮助下,我能够验证两件事:1。result = work.params ['billingid']返回字符串2.我能够从任何控制器保存到不同的模型

但是,即使我有attr_accessible:billing_id,我仍然无法将结果保存到User表的billing_id列中。 我成功地将结果保存在Store表的store_name列中,因此我不知道用户模型阻止我保存的内容。

我跑了,

@mystore = Store.find(current_user)
@mystore.store_name = result            
@mystore.save

它很成功。 但,

@thisuser = User.find(current_user)
@thisuser.billing_id = result
@thisuser.save

即使正确设置了attr_accessible,这也会失败。 除了attr_accessible之外还有什么可以阻止保存某些属性? 感谢大家!

更新2:用户模型

要求'消化'

class User <ActiveRecord :: Base

has_one :store
has_many :products
attr_accessor :password
# attr_accessible was commented out completely just to check as well. Neither worked
attr_accessible :name, :email, :password, :password_confirmation, :username, :billing_id
validates :name,  :presence => true,
                :length   => { :maximum => 50 }

validates :email, :presence => true,
                :format   => { :with => email_regex },
                :uniqueness => { :case_sensitive => false } 
validates :password, :presence     => true,
                   :confirmation => true,
                   :length       => { :within => 6..40 } 

username_regex = /^([a-zA-Z0-9]{1,15})$/

before_save :encrypt_password

def has_password?(submitted_password)
    encrypted_password == encrypt(submitted_password)
end
private
def encrypt_password
  self.salt = make_salt if new_record?
  self.encrypted_password = encrypt(password)
end

def encrypt(string)
  secure_hash("#{salt}--#{string}")
end

def make_salt
  secure_hash("#{Time.now.utc}--#{password}")
end

def secure_hash(string)
  Digest::SHA2.hexdigest(string)
end

结束

UPDATE FINAL:解决方案使用@ thisusers.errors,我能够发现它在此请求期间尝试验证密码的存在。 一旦我评论出来,它就没有问题地保存了。 我不确定为什么会这样,但我会从这里开始。 谢谢大家,特别感谢。 dmarkow!

从控制器更新任意数量的模型应该没有问题。

  1. 确保work.params['billingid']实际上包含一个值。

  2. 您的User模型可能有一些标记为attr_accessible属性(因为您有current_user ,我假设您有身份验证,这通常意味着需要默认保护您的模型的属性)。 如果是这种情况,则意味着只能通过质量分配来更改这些属性(例如,使用update_attributes )。 无论是添加billing_id到的属性列表attr_accessible ,或者不使用质量分配。 (相反,你只需要执行current_user.billing_id = result然后执行current_user.save

编辑:问题结果是User模型上的验证错误。 user.save返回false时,请务必检查user.errors

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM