Formオブジェクトの書き方について
Q&A
解決したいこと
クレジットカード情報(token)はpurchasesテーブル、住所はaddresesテーブルに保存したくFormオブジェクトを用いていますが画像のようにうまくいきません。どうしたらいいのでしょうか?
発生している問題・エラー
出ているエラーメッセージを入力
該当するソースコード
class Address < ApplicationRecord
belongs_to :purchase
end
class Purchase < ApplicationRecord
attr_accessor :token
validates :token, presence: true
belongs_to :user
belongs_to :item
has_one :address
end
class PurchaseAddress < ApplicationRecord
extend ActiveHash::Associations::ActiveRecordExtensions
include ActiveModel::Model
attr_accessor :post_number, :municipality, :prefecture_id, :phone_number, :token
belongs_to :prefecture
with_options presence: true do
validates :post_number, format: { with: /A\d{3}[-]\d{4}z/, message: 'Input correctly' }
validates :municipality
validates :prefecture_id, numericality: { other_than: 1, message: 'Select' }
validates :address
validates :phone_number, format: { with: /A\d{11}z/, message: 'Input only number' }
validates :token
end
def save
user = User.create(nickname: nickname, name: name,family_name: family_name,namekana: namekana,family_namekana: family_namekana, birth: birth)
item = Item.create(name: name, text: text, price: price, state_id: state_id, category_id: category_id, prefecture_id: prefecture_id, burden_id: burden_id, shippingday_id: shippingday_id, image: image)
Purchase.create(user_id: current_user.id, item_id: item_id, token: token)
Address.create(post_number: post_number, municipality: municipality, prefecture_id: prefecture_id, addresses: addresses, phone_number: phone_number,user_id: current_user.id)
end
end
class AddressesController < ApplicationController
def index
@purchase_address = PurchaseAddress.new
end
def create
@purchase_address = PurchaseAddress.create(address_params)
if @purchase_address.valid?
pay_item
@purchase_address.save
return redirect_to root_path
else
render 'index'
end
end
private
def address_params
params.permit(:post_number, :municipality, :prefecture_id, :phone_number, :token)
end
def pay_item
Payjp.api_key = ENV["PAYJP_SECRET_KEY"]
Payjp::Charge.create(
amount: item_params[:price],
card: purchase_params[:token],
currency:'jpy'
)
end
end
自分で試したこと
Formオブジェクトの記述、各モデルのアソシエーションの確認
0