jeudi 8 juin 2017

Selecting multiple days of the week with checkboxes in Rails form

I've looked around at a lot of other threads on building checkboxes in Rails, but I can't seem to find the answer to this particular question.

I have a form where users can select multiple days of the week when they want something to happen, so I have a checkbox representing each day of the week. This gets submitted as an array. My :days column in the database accepts integers.

When I submit the form, there's no error, the :days param looks right, but the array doesn't get inserted into the database. Does anyone know why that might be? The params are strings, so does that mean I need to convert everything to integers first? I tried changing the db to accept strings instead and it works fine, but for some reason I can't get it to accept integers.

I'm open to a different approach as well if there's a better way to handle these dates. I just thought integers would lead to fewer errors than saving them as strings.

Thanks! Let me know if I can provide anything else.

# View

<div class="form-group">
    <%= f.label :days %><br/>
    <% Date::DAYNAMES.each_with_index do |day, i| %>
        <%= f.check_box :days, { multiple: true }, i %>
        <%= day %>
    <% end %>
</div>


# Controller

def create
    @check_in = current_user.check_ins.build(check_in_params)
    if @check_in.save
        @check_in.update(team_id: current_user.team.id)
        redirect_to check_ins_path, flash: { notice: "Check-in successfully created." }
    else
        redirect_to check_ins_path, flash: { alert: @check_in.errors.full_messages }
    end
end

private
    def check_in_params
        params.require(:check_in).permit(:question, :frequency, team_member_ids: [], days: [])
    end




Aucun commentaire:

Enregistrer un commentaire