LoginSignup
0
0

More than 3 years have passed since last update.

ActiveHashはアソシエーションをしっかり設定しよう

Last updated at Posted at 2020-10-27

※結果を知りたい方は下の方までスクロールしてください。

エラー発生

商品を出品する機能を実装中のこと…

d812404dd725355d1e491026dce6f911.png
何これ…初めて見た…

原因を探る

コントローラーの記述は間違ってないよね…

item_controller.rb 一部割愛
class ItemsController < ApplicationController

  def create
    @item = Item.new(item_params)
    if @item.valid?
      @item.save
      redirect_to root_path
    else
      render :new
    end
  end

  private
  def item_params
    params.require(:item).permit(:name, :info, :price, :category_id, :status_id, :delivery_charge_id, :shipment_source_id, :date_of_shipment_id).merge(user_id: current_user.id)
  end

end

うん…大丈夫

ええー
じゃあモデルかなぁ

item.rb
class Item < ApplicationRecord

  validates :name, :info, :price, presence: true
  validates :category_id, :status_id, :delivery_charge_id, :shipment_source_id, :date_of_shipment_id, numericality: { other_than: 1 }

  belongs_to :user
  has_many   :comments
  has_one    :buyer

  extend ActiveHash::Associations::ActiveRecordExtensions
  belongs_to_active_hash :category, :status, :delivery_charge, :shipment_source, :date_of_shipment
end

いや、記述の抜け漏れもないし、半角全角もスペルも大丈夫
バリデーションも大丈夫(←これが落とし穴)

ビューファイル(割愛)は…うーん大丈夫そう

そして、インターネットの海を彷徨うこと30分…
本当にわからん

しゃあないか

助け舟を呼ぶことに

大海に投げ出されたような気分だったのでもうこれは人に聞くしかあるまい
某短期講習中なので頼もしい方々に聞くことはできる

早速原因究明に向けて色々と思案してくださった
ありがたや〜😌

これを、あれを試し、色々触っていった結果どうやらモデルの記述に問題があった模様

class Item < ApplicationRecord

  validates :name, :info, presence: true
  validates :price, presence: true
  validates :category_id, :status_id, :delivery_charge_id, :shipment_source_id, :date_of_shipment_id, numericality: { other_than: 1 }

  belongs_to :user
  has_many   :comments
  has_one    :buyer

  extend ActiveHash::Associations::ActiveRecordExtensions
  belongs_to_active_hash :category
  belongs_to_active_hash :status
  belongs_to_active_hash :delivery_charge
  belongs_to_active_hash :shipment_source
  belongs_to_active_hash :date_of_shipment

end



↓つまりはこの部分↓

  belongs_to_active_hash :category
  belongs_to_active_hash :status
  belongs_to_active_hash :delivery_charge
  belongs_to_active_hash :shipment_source
  belongs_to_active_hash :date_of_shipment

ここを別々に書くだけ!
バリデーションなんやからまとめて書かせてくれや…と思ったが、

この話をしていると聞いていたうちの一人が






「それバリデーションじゃなくてアソシエーションですよ」






…まじかぁ…
まじかぁぁぁぁ!!!

恥ずかしいぃ!///
そういやそうだわ!思いっっきりBelongs_toって書いてあるし!
なんなら俺がActiveHashを導入してた時にrails gで生成してたものは?

モデルだよ!
モデルを生成してたんだよ!
それを関連付けるんだからアソシエーション以外に何があんの!

知らなかったとはいえ思いつく材料は目の前にあった訳だ
反省するとともに判断材料が増えたので一歩前進したと思う


本当に今回は勉強になった
真摯に対応してくれた方ありがとうございました

0
0
1

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