如何将数组分解为字符串MVC?

时间:2015-08-13 01:42:48

标签: ruby-on-rails arrays ruby session model-view-controller

如果current_user提出习惯,:committed这样做的日子就是这样:

  
      
  1. db t.text "committed", default: ["sun", "mon", "tue", "wed", "thu", "fri", "sat"], array: true
  2.   
  3. 习惯/ _form <%= f.collection_check_boxes :committed, Date::ABBR_DAYNAMES, :downcase, :to_s %>(用户选择日期)
  4.   
  5. habit_controller habit_params :committed => []
  6.   
  7. 习惯/指数 <% habit.committed.map { |d| d.titleize[0,3] }.each do |title| %> <%= title %> <% end %>
  8.   

如果nil用户提出习惯(建议他在注册前创建一个习惯),那么他:committed这样做的日子就是这样:

  
      
  1. db t.text "committed", default: ["sun", "mon", "tue", "wed", "thu", "fri", "sat"], array: true
  2.   
  3. 习惯/ _form <%= f.collection_check_boxes :committed, Date::ABBR_DAYNAMES, :downcase, :to_s %>(用户选择日期)
  4.   
  5. * habit_controller session[:habit_committed] = [params["habit"]["committed"]]
  6.   
  7. * users_controller committed = session.delete(:habit_committed) @user.habits.create(committed: committed)
  8.   
  9. 习惯/指数 <% habit.committed.map { |d| d.titleize[0,3] }.each do |title| %> <%= title %> <% end %>
  10.   

enter image description here

当两个习惯首次提交时,终端看起来像这样:

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(',')但我和#39 ;我猜我没有使用正确的混合物或格式。

很抱歉如果此问题的布局看起来像ransom便条。

第一次尝试

  
      
  1. db 更改为t.text "committed", default: "---\n- sun\n- mon\n- tue\n- wed\n- thu\n- fri\n- sat\n"
  2.   
  3. habit.rb serialize :committed, Array
  4.   
  5. 习惯/ _form <%= f.collection_check_boxes :committed, Date::ABBR_DAYNAMES, :downcase, :to_s %>(用户选择日期)
  6.   
  7. habit_controller session[:habit_committed] = [params["habit"]["committed => []"]]
  8.   
  9. * users_controller committed = session.delete(:habit_committed) @user.habits.create(committed: committed)
  10.   
  11. 习惯/指数 <% habit.committed.map { |d| d.titleize[0,3] }.each do |title| %> <%= title %> <% end %>
  12.   

这产生了:["committed", "---\n- \n"]

1 个答案:

答案 0 :(得分:1)

当您为已提交设置会话变量时,您将其设置为空数组,然后获取一个空数组作为值。

在你的日志中, params [&#34;习惯&#34;] [&#34;已提交&#34;] 的值已经是一个数组,因此无需重新解析它或将其嵌入其他括号内

所以试一试:

  

habit_controller.rb 会话[:habit_committed] =参数[&#34;习惯&#34;] [&#34;已提交&#34;]。拒绝(&amp;:空?)< / p>