如果 current_user
提交一个习惯,他的日子:committed
像这样工作:
- db
t.text "committed", default: ["sun", "mon", "tue", "wed", "thu", "fri", "sat"], array: true
- habits/_form
<%= f.collection_check_boxes :committed, Date::ABBR_DAYNAMES, :downcase, :to_s %>
(user chooses days)- habits_controller
habit_params :committed => []
- habits/index
<% habit.committed.map { |d| d.titleize[0,3] }.each do |title| %> <%= title %> <% end %>
如果 nil
用户提交一个习惯(鼓励他在注册前创建一个),他的日子 :committed
像这样工作:
- db
t.text "committed", default: ["sun", "mon", "tue", "wed", "thu", "fri", "sat"], array: true
- habits/_form
<%= f.collection_check_boxes :committed, Date::ABBR_DAYNAMES, :downcase, :to_s %>
(user chooses days)- *habits_controller
session[:habit_committed] = [params["habit"]["committed"]]
- *users_controller
committed = session.delete(:habit_committed)
@user.habits.create(committed: committed)
- habits/index
<% habit.committed.map { |d| d.titleize[0,3] }.each do |title| %> <%= title %> <% end %>
当这两个习惯首次提交时,终端看起来像这样:
Started POST "/habits" for 127.0.0.1 at 2015-08-11 13:15:40 -0400
Processing by HabitsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"EDxn180pxfaqNCBNtzxJd3Y0XHO5m9eURhj9WOf25Re64ed0f99HlIXIgHfNpyJIi1KD92SQ/QggcTCf7pZPHw==", "habit"=>{"committed"=>["sun", "mon", "tue", "wed", "thu", "fri", "sat", ""], "date_started(2i)"=>"8", "date_started(3i)"=>"11", "date_started(1i)"=>"2015", "trigger"=>"test", "action"=>"test", "target"=>"test", "reward"=>"test"}, "button"=>""}
Redirected to http://0.0.0.0:3000/valuation_signup
Completed 302 Found in 11ms (ActiveRecord: 0.0ms)
但它们的不同之处在于当用户完成注册时我看到终端得出这样的结论:["committed", "{{NULL}}"]
或 ["committed", "{NULL}"]
或 ["committed", "{}"]
.
我尝试了多种方法,例如 .join
, .split
, .inspect
, .map
, .map(&:inspect).join(', ')
, .map {|str| "\"#{str}\""}.join(',')
但我猜我没有使用正确的混合物或格式。
抱歉 如果这个问题的布局看起来像 ransom
注意。
第一次尝试
- Changed db to
t.text "committed", default: "---\n- sun\n- mon\n- tue\n- wed\n- thu\n- fri\n- sat\n"
- habits.rb
serialize :committed, Array
- habits/_form
<%= f.collection_check_boxes :committed, Date::ABBR_DAYNAMES, :downcase, :to_s %>
(user chooses days)- habits_controller
session[:habit_committed] = [params["habit"]["committed => []"]]
- *users_controller
committed = session.delete(:habit_committed)
@user.habits.create(committed: committed)
- habits/index
<% habit.committed.map { |d| d.titleize[0,3] }.each do |title| %> <%= title %> <% end %>
这产生了:["committed", "---\n- \n"]
最佳答案
当您为 committed 设置 session 变量时,您将其设置为一个空数组,然后获取一个空数组作为值。
在您的日志中,params["habits"]["committed"] 的值已经是一个数组,因此无需重新解析它或将其嵌套在其他括号中
所以试一试:
habits_controller.rb session[:habit_committed] = params["habit"]["committed"].reject(&:empty?)
关于ruby-on-rails - 如何将数组分解为字符串 MVC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31978181/