3

これは私のコードです:

クラス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) 保存しようとしています。UsersController以外のからUserモデルの属性を更新することはできませんか?billingid:billing_id

簡単に言えば、モデル#2のコントローラーからモデル#1の属性を更新することはできませんか?

ありがとう

更新:以下の男性の助けを借りて、2つのことを確認できました: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:ユーザーモデル

「ダイジェスト」が必要

クラス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

エンドエンド

最終更新:@ thisusers.errorsを使用した解決策では、このリクエスト中にパスワードの存在を検証しようとしていることがわかりました。コメントアウトすると、問題なく保存されました。なぜこれが起こっているのかわかりませんが、ここから取り上げます。みんな、特にありがとう。dmarkow!

4

1 に答える 1

3

コントローラからモデルをいくつでも更新しても問題はありません。

  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.errorswhenuser.saveがfalseを返すことを常に確認してください。

于 2011-04-08T06:37:43.683 に答える