LoginSignup
0
0

More than 3 years have passed since last update.

Formオブジェクトではrailsで仕組まれた「save」設定ではない

Last updated at Posted at 2021-04-25

バリデーションは、データベースを永続化するうえで極めて重要です。そのため、save、updateメソッドは、バリデーションに失敗するとfalseを返します。このとき実際のデータベース操作は行われません。

→そのように仕組まれているということです。

Railsガイド
https://railsguides.jp/active_record_basics.html#%E3%83%90%E3%83%AA%E3%83%87%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3%EF%BC%88%E6%A4%9C%E8%A8%BC%EF%BC%89

Formオブジェクトでは

基本自作したフォームオブジェクトではsaveやupdateの際に上記で書いた付加されたrails独自の設定は全くない(=バリデーションに失敗するとfalseを返したりはしない)ので基本、下に示した上部と下部は無関係なので関連性なくプログラムが通リます。

address_purchase.rb(上部)
with_options presence: true do
   validates :address 
   validates :postal_code, format: { with: /\A[0-9]{3}-[0-9]{4}\z/, message: "は登録できません。ハイフン-(半角)を含みます。"}
   validates :town, format: { with: /\A[ぁ-んァ-ン一-龥々]/, message: "は全角ひらがな、全角カタカナ、漢字で入力して下さい" }
   validates :phone_number, format: { with: /\A\d{10,11}\z/, message: "は半角数値で入力して下さい" }
   validates :prefecture_id, numericality: { other_than: 1} 
end
address_purchase.rb(下部)
def save
   purchase = Purchase.create(user_id: user_id, item_id: item_id)
   Address.create(postal_code: postal_code, prefecture_id: prefecture_id, town: town, address: address, building: building, phone_number: phone_number, purchase_id: purchase.id)
end
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0