1

In a Rails 4 form_for form, I'm have:

f.check_box :visible

I want the checkbox to be rendered as checked when rendering the form for a brand new (ie unsaved) object.

When the object is saved, I want the checkbox to behave normally (ie be checked or not checked based on the value of the saved object).

This works:

f.object.new_record? ? (f.check_box :visible, :checked => true) : (f.check_box :visible)

.. but it's pretty long! Is there a simpler/better way I can accomplish this?

1
  • Why not set visible to true on the unsaved record? Commented Feb 1, 2016 at 19:23

2 Answers 2

2
f.check_box :visible, checked: ( f.object.new_record? || f.object.visible )
Sign up to request clarification or add additional context in comments.

Comments

0

Just set the attribute to true when you create your new object in the controller:

def new
   @model = Model.new(visible: true)
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.