开发者

How to store week-days as a CSV in a string field?

开发者 https://www.devze.com 2023-02-13 07:47 出处:网络
My intention is to display 7 checkboxes, 1 for each day of the week, and save it in a single field in a table, in CSV format. (So, Sunday,Wednesday would be saved as string 0,3)

My intention is to display 7 checkboxes, 1 for each day of the week, and save it in a single field in a table, in CSV format. (So, Sunday,Wednesday would be saved as string 0,3)

So, I am able to get the CSV of the selected week days into the field.

But when I edit the form, all the checkboxes are unchecked. How do I get the checkboxes to be selected, based upon the CSV i开发者_运维百科n the field?>

This is how I am showing the checkboxes in the form:

<% Date::DAYNAMES.each_with_index do |day,index| %>
  <%= check_box_tag "post[week_days_#{index}]", index, false, 
                    :name => "post[week_days][]" %>
<% end %>

Output is:

...
<input id="post_week_days_0" name="post[week_days][]" type="checkbox" value="0" />
<input id="post_week_days_1" name="post[week_days][]" type="checkbox" value="1" />
...

I think I have to change the form like below (added the :checked option):

<%= check_box_tag "post[week_days_#{index}]", index, false,
                  :name => "post[_week_days][]", 
                  :checked => (post.week_days.include? index ? true : false) %>

But how will I get the include? to work, since the field is a string, and I somehow need that string as an array?

Ps. This is the way I am trying to implement this, but if there is some better way to do this, I could use that way..


You could do

:checked => (post.week_days.include? index.to_s)

You dont have to give ?(ternary) condition because .include? returns true or false

0

精彩评论

暂无评论...
验证码 换一张
取 消