Search code examples
ruby-on-railsdatabaseruby-on-rails-4ruby-on-rails-5

How Do I save it to the database?


I'am Making a form which has checkboxes with values true or false.

<%= form_tag url_for(action: 'create'), method: "post" do %>
<tbody>
  <tr>
  <td class="image"> <%= image_tag("https://cdn.iris.nitk.ac.in/images/new_dashboard/button_Human.png", class: 'list_image') %></td>
  <td>Profile</td>
  <td><%= check_box_tag '1', true, true, :checked => true, data: {toggle: "toggle", on: "Yes", off: "No", onstyle: "success", offstyle: "danger"} %></td>
  </tr>
  <tr>
  <td class="image"> <%= image_tag("https://cdn.iris.nitk.ac.in/images/new_dashboard/withdraw.png", class: 'list_image') %></td>
  <td>Withdraw Admission</td>
  <td><%= check_box_tag '2', true, true, :checked => true, data: {toggle: "toggle", on: "Yes", off: "No", onstyle: "success", offstyle: "danger"} %></td>
  </tr>
  <tr>
  <td class="image"> <%= image_tag("https://cdn.iris.nitk.ac.in/images/new_dashboard/button_academics.png", class: 'list_image') %></td>
  <td>Course Registration</td>
  <td><%= check_box_tag '3', true, true, :checked => true, data: {toggle: "toggle", on: "Yes", off: "No", onstyle: "success", offstyle: "danger"} %></td>
  </tr>
</tbody>
"btn btn-primary btn-lg btn-block %>

upon submitting it takes me to this create action in controller.

def create
1.upto(13) do |i|
  (params[:i] ? (current_user.misc_data[:pin_modules] ||= []) << i : next)
end
redirect_to '/'

end end

where pin_modules is an array that i want to create inside user model's misc_data hash. i don't get any error while submitting but when i check db there's no array and nothing is saved. Can anyone please help me out?


Solution

  • You're updating the objects attributes but as you say not saving them to the DB. Try:

    def create
      current_user.misc_data[:pun_modules] ||= []
    
      (1..13).each do |i|
        next unless params[:i]
        current_user.misc_data[:pin_modules] << i
      end
    
      current_user.save
      redirect_to '/'
    end
    

    Or if you wanted to keep your ternary, just add a current_user.save before you redirect