【发布时间】:2011-08-01 05:35:42
【问题描述】:
这是我的代码:
类 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 更新 User 模型的属性?
简单地说,是不是不能从模型#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:用户模型
需要“摘要”
类用户<: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
结束 结束
更新最终:解决方案 使用@thisusers.errors,我发现它在此请求期间试图验证密码的存在。一旦我将其注释掉,它就会毫无问题地保存。我不确定为什么会这样,但我会从这里开始。谢谢大家,尤其是。 dmarkow!
【问题讨论】:
-
控制器实际上只是一种组织应用程序功能的方式,您可以在任何控制器中使用任何模型。上面显示的代码看起来不错,假设
current_user是一个可访问的方法,它返回具有billing_id属性的模型实例(大概是User)。
标签: ruby-on-rails update-attributes