[英]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!
從控制器更新任意數量的模型應該沒有問題。
確保work.params['billingid']
實際上包含一個值。
您的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.