0

Background

In my app, users can choose multiple languages which they're able to speak on their profile edit page (users/edit.html.erb) from checkbox. Many-to-many relation is already written, so multiple data can be saved properly.

Now, when users came back to their profle edit page, all the checkbox are displayed in a blank. I would like to display languages with "checked" which user chose and saved.

users/edit.html.erb

<li>
 <div class="col-1">Spoken languages:</div>
   <div class="col-2">      
     <label><input type="checkbox" name="language[]" value="1">Japanese</label>
     <label><input type="checkbox" name="language[]" value="2">English</label>
     <label><input type="checkbox" name="language[]" value="3">Chinese</label>
     <label><input type="checkbox" name="language[]" value="4">Spanish</label>
  </div>    
</li> 

What I tried to do

I searched this kind of function, but I only found how to make a specific initial value (such as always check "English"). I would be grateful if someone give me advice.

Version

ruby 2.6.4p104 RubyGems 3.0.3 Rails 5.2.3

Pranav MS
  • 2,235
  • 2
  • 23
  • 50
punpun36
  • 13
  • 4
  • 1
    hi, perhaps use `check_box` https://stackoverflow.com/questions/13616554/how-to-make-a-check-box-checked-in-rails – IronMan Jan 22 '21 at 03:40
  • 3
    Does this answer your question? [How to make a check\_box checked in rails?](https://stackoverflow.com/questions/13616554/how-to-make-a-check-box-checked-in-rails) – zhisme Jan 22 '21 at 08:43
  • Why don't you use https://apidock.com/rails/ActionView/Helpers/FormHelper/check_box along with https://apidock.com/rails/v5.2.3/ActionView/Helpers/FormHelper/form_for. When you are working with erb file form is the option – Jagdish Jan 22 '21 at 22:34

1 Answers1

0

I was able to figure it out with include method. Thank you very much.

<label><input type="checkbox" name="language[]" value="1" <%= "checked='checked'" if @user.language_ids.include?(1) %>>Japanese</label>
<label><input type="checkbox" name="language[]" value="2" <%= "checked='checked'" if @user.language_ids.include?(2) %>>English</label>
<label><input type="checkbox" name="language[]" value="3" <%= "checked='checked'" if @user.language_ids.include?(3) %>>Chinese</label>
<label><input type="checkbox" name="language[]" value="4" <%= "checked='checked'" if @user.language_ids.include?(4) %>>Spanish</label>
punpun36
  • 13
  • 4