In Ruby on Rails -to dislpay day[Sun, Mon, Tue,...] instead of boolean field true/false in rails

Viewed 96

I am working on the project where I have to schedule the events. While adding events user can select multiple days on a checkbox. You can view the figure here.

Select the days when the event will occur.

for this I have have created database as

  def change
    add_column :schedules, :sunday, :boolean
    add_column :schedules, :monday, :boolean
    add_column :schedules, :tuesday, :boolean
    add_column :schedules, :wednesday, :boolean
    add_column :schedules, :thursday, :boolean
    add_column :schedules, :friday, :boolean
    add_column :schedules, :saturday, :boolean
  end

My partial form to select days looks like x-special/nautilus-clipboard copy

.field
= f.check_box :sunday
= f.label :day, "Sunday",class:"mx-2"
br
= f.check_box :monday
= f.label :day, "Monday",class:"mx-2"
br
= f.check_box :tuesday
= f.label :day, "Tuesday",class:"mx-2"
br
= f.check_box :wednesday
= f.label :day, "Wednesday",class:"mx-2"
br
= f.check_box :thursday
= f.label :day, "Thursday",class:"mx-2"
br
= f.check_box :friday
= f.label :day, "Friday",class:"mx-2"
br
= f.check_box :saturday
= f.label :day, "Saturday",class:"mx-2"

The problem I am facing is that I fill up the form and as a result I am getting true of fase while listing because of boolean field. I want to change the result shown in index page to sunday, moday,... x-special/nautilus-clipboard copy

displaying day as true or fasle I have pass the parameter on controller as

 def schedule_params
    params.require(:schedule).permit(:name,:begindate,:enddate,:campaign_id,:sunday,:monday,:tuesday*,:wednesday,:thursday,:friday,:saturday)<br>
 end

Thanks in advance!! Ignore my way of posting because i am new here and this is my first post

2 Answers

I think the answer of @Mosaaleb is good enough

Mine version is:

def occur_days
  days = %w[sunday monday tuesday wednesday thursday friday saturday]
  days.select { |d| attributes[d] }.join(', ')
end

schedule.sunday = true
schedule.friday = true
schedule.occur_days
# => sunday, friday

You can write a method in your schedule model to map daynames strings to your schedules day values:

def day_names
  Date::DAYNAMES.zip([sunday, monday, tuesday, wednesday, thursday, friday, saturday]).to_h
end

This would return something like:

schedule.day_names
# => {"Sunday"=>true, "Monday"=>true, "Tuesday"=>false, "Wednesday"=>false, "Thursday"=>false, "Friday"=>true, "Saturday"=>true}

Then use it in your views display the days that have true value

Related