1

Is there a cleaner way of selecting a radio_button by default or if it was previously selected in one line of code?

I first tried this:

- if @job.new_record?
  = f.radio_button :environment_id, env.id, :checked => env.is_default
- else
  = f.radio_button :environment_id, env.id, :checked => @job.environment == env

I tried to refactor using this:

= f.radio_button :environment_id, env.id, :checked => (@job.andand.environment == env) || env.is_default

but the problem with that is if the default selection is AFTER the job's environment, it will select the default selection.

Any other suggestions?

2 Answers 2

2

I would probably just set the default value for the model in the controller. That logic should not be placed in the views. I don't know exactly how that would work for you because I don't know the structure of your models or where the "default" value comes from, but if you set the default value in the controller then the radio button will be selected if it matches the env.id in your case

# In Controller
@job = Job.new(:environment_id => "foo")

# In the view
= f.radio_button :environment_id, "foo"
= f.radio_button :environment_id, "bar"

In this case, the first radio button will be selected.

Sign up to request clarification or add additional context in comments.

5 Comments

default value is a field in the Environment model(job has one environment) and it can be checked using environment.is_default? also, there's a possibility there's no default environment
Okey, then set that value in the controller, should work fine
is there a solution that should not involve setting it in the controller?
Probably, but it goes against the whole MVC concept that rails has. By doing that, you lose the goodness that comes with the rails form helpers. But if you're dead set on doing it in the views, then it would be good to know a bit more about the logic you want to enforce. My guess is that IF @job has an environment_id, select that radio_button, but IF enivronment_id is nil, then use the default, is that correct?
yup that is correct(sorry it took so long to get back to this)
0

use radio_button_tag

=radio_button_tag environment_id, env.id, (@job.andand.environment == env)

1 Comment

and what about the default? will it be checked if it's a new job?

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.