1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

開発メモ rails fields_for

Last updated at Posted at 2019-10-03

業務で必要だったのでメモ書き。

viewで一括登録したい時、fields_forを使って登録しようとした。

以下source

_form.html.erb
<%= f.fields_for :user_details, @user.user_details.sort_by(&:order_number) do |sf| %>
    <% isDisabled = sf.diplay_flg ? true : false %>
    <%= sf.number_field :type2_flat1_amount,{class: "money", disabled: isDisabled } %>
<% end %>

fields_forで指定したテーブルの値を表示判定で使いたかったので、調べた結果

例.×
#undefined method errorが発生
sf.diplay_flg
例.○
#objectを挟む 
sf.object.diplay_flg

フォーム名.object.カラム名
というようにobjectを間に咬ませると値が取れるっぽい。

RailsFormHelperの機能とのこと。

修正後

_form.html.erb
<%= f.fields_for :user_details, @user.user_details.sort_by(&:order_number) do |sf| %>
    <% isDisabled = sf.object.diplay_flg ? true : false %>
    <%= sf.number_field :type2_flat1_amount,{class: "money", disabled: isDisabled } %>
<% end %>

今後よく使いそうなのでメモに残しておく。

開発環境
ruby 1.9.2
rails 3.0.5

参考の記事は以下。
助かりました。ありがとうございます。
https://codeday.me/jp/qa/20181229/94333.html

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?