LoginSignup
53

More than 5 years have passed since last update.

FormオブジェクトのURLの渡し方について

Posted at

Rails Advent Calendarの2日目の記事である Rails4でFormオブジェクトを作る際に気をつける3つのポイント|江の島エンジニアBlog を読んだんですが、ちょっと気になる所があったんで突っ込みを入れてみる。

モデル層であるFormオブジェクトにURLを返すためのメソッド定義するのは、あんまりよろしく無いんじゃないかと思う。
そもそもurl_helperをちゃんと動かすためにはホスト名やポート等のリクエスト情報が必要で、この例の様に相対パスを出力するだけなら使えなくもないけどモデル層から呼ばれることは、余り想定されていない。
デコレーター層に生やすか、そもそも組込みのヘルパーを使うべきではないかと思う。

ちなみにform_forヘルパーが中で使っているのはpolymorphic_pathというヘルパーで、地味だし自分も良く忘れるのだが、この例ではこれがそのまま使えるはず。

- form_for @site_form, url: polymorphic_path(@site_form.site) do

これで、Formオブジェクトのurlメソッドは必要無くなるし、persisted?かどうかの分岐も不要になる。こういう感じでいかがだろうか?
もうちょっと出力フォーマットが複雑だったら、やっぱりデコレーターかなあ。

ついでにもう一つ。Rails4なら、

extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations

って書かなくても、

include ActiveModel::Model

で良い。

ActiveModel::Modelは以下と等価。

  • extend ActiveModel::Naming
  • extend ActiveModel::Translation
  • include ActiveModel::Validations
  • include ActiveModel::Conversion

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
53