2017-08-04 8 views
0

モデルユーザーSimple_form&ネストされた属性があるため、日付の空白のモデルを保存

class User < ApplicationRecord 
    has_many :experiences, dependent: :destroy 
    accepts_nested_attributes_for :experiences, reject_if: :all_blank, allow_destroy: true 
end 

モデル体験

class Experience < ApplicationRecord 
    belongs_to :user 
end 

VIEW(_experience_fields_user.html)

<div class="nested-fields"> 
    <%= f.input :start_date as: :date, discard_day: true, order: [:month, :year], start_year: Date.today.year , end_year: Date.today.year - 37 %> 
</div> 

で私の入力を=属性>それで、「月」と「年」の2つのフィールドが表示されます

私は自分のフォームを送信した場合、空のフィールドでのparamsは、次のとおりです。

"expertise"=>"", "start_date(3i)"=>"1", "start_date(2i)"=>"", "start_date(1i)"=>"" 

私の問題: "START_DATE(3I)" => "1"

これはparamsはは(それが表しています空白ではありませんビューに表示されない日の値)、ネストされた属性の条件を完了することを許可しない "reject_if :: all_blank"

月と年が空白の場合、1日の値を変更する方法はありますか? Thxを

+0

あなたは可能性がありますあなたのフォームの 'as::date'を' as::string'に置き換えることで、動作させてください。 – Belder

+0

それは入力の動作を変更し、良いユーザーエクスペリエンスのための最良の方法ではありません – Etienne

+0

そうです。私は過去にもこの問題を抱えていて、それをどのように解決したかを覚えようとしています。 [This](https://stackoverflow.com/questions/29075404/how-can-i-generate-inputtype-date-with-simple-form)は1つのオプションかもしれません。 – Belder

答えて

1

私は最終的に方法を見つけた:

別の入力が空である場合、私はテストのための条件を作成した(この場合のCOMPANY_NAMEに)

を私のモデルのユーザーの場合:

accepts_nested_attributes_for :experiences, reject_if: :reject_xp, allow_destroy: true 

def reject_xp(attributes) 
    attributes['start_date(3i)'] == "1" && attributes['company_name'].blank? 
end 
関連する問題