【问题标题】:Ruby on Rails: Mass-Assignment on iteration in loop?Ruby on Rails:循环迭代中的质量分配?
【发布时间】:2014-04-24 08:19:55
【问题描述】:

我遇到了批量分配错误。

Can't mass-assign protected attributes: 1, 2, 3, 4, 5, 6, 7

这些数字代表此循环中的迭代:

<% (1..7).each do |i| %>
  <%= select_tag "hour[#{i}][day]", options_for_select(days_hours) %>
<% end %>

这是在我的模型中:

attr_accessible :day, :open_time, :close_time

我正在尝试创建一个这样的数组:

"hour"=>{
 "1"=>{"day"=>"Sunday","open_time"=>"6","close_time"=>"6"},
 "2"=>{"day"=>"Sunday","open_time"=>"6","close_time"=>"6"},
 "3"=>{"day"=>"Sunday","open_time"=>"6","close_time"=>"6"}
}

我正在尝试将新行中的每个迭代保存到数据库中

def create
  @hour = @hourable.hours.new(params[:hour])
end

如何修复迭代质量分配?还是我做错了?

谢谢!

【问题讨论】:

  • 请说明您希望应用程序做什么。很难从您的代码中分辨出来。什么是班级? select_tag 的用户设置是什么?
  • “我正在尝试创建一个这样的数组:”这是一个哈希,这可能是您的问题的一部分,该数组看起来像这样:hours = [{"day"=&gt;"Sunday","open_time"=&gt;"6", "close_time"=&gt;"6"}, {"day"=&gt;"Monday","open_time"=&gt;"6", "close_time"=&gt;"6"},{"day"=&gt;"Tuesday","open_time"=&gt;"6", "close_time"=&gt;"6"}]
  • @Isotope 是有道理的。你认为你可以帮我在不需要数字的地方得到它吗?我尝试删除#{i},并且只有hour[day] 之类的东西,我收到Internal Server Error 并带有以下消息:expected Array (got String) for param day'`
  • @andrewliu:请更新您的问题,详细说明要求。可能是您可以提供的整个视图内容,以及您希望如何显示选择标签、其值以及您希望如何将其保存在数据库中,:open_time:close_time 等值是什么。
  • &lt;%= select_tag "hour[i][open_time]", options_for_select(days_hours) %&gt; &lt;%= select_tag "hour[i][close_time]", options_for_select(days_hours) %&gt; &lt;%= hidden_field_tag "hour[i][day]", value: i %&gt; 那么你只需要把day int变成一个字符串

标签: ruby-on-rails ruby ruby-on-rails-3 mass-assignment


【解决方案1】:

从哈希中,Active Record 假定“1”、“2”和“3”是模型的列名或属性,并且由于您没有为访问列指定 attr_accessible 选项,它会抛出 @987654323 @。否则,您需要按如下方式创建哈希:

"hour"=>{
"day"=>"Sunday",
"open_time"=>"6",
"close_time"=>"6"}
}

希望对你有帮助:)

【讨论】:

  • 有道理。我想知道您是否可以帮助我扩展我最初的问题。我该怎么做才能让我的数组变成这样?如果我从括号中删除#{i} 并使其像"hour[day][]",则所有值都将进入一个数组,并且不会像上面评论中提到的@Isotope 那样拆分。像这样hours = [{"day"=&gt;["Sunday","Monday",Tuesday"]...等等等等...
  • 我创建了一个新问题:stackoverflow.com/questions/23272276/…
【解决方案2】:

你的小时属性是

"hour" => {
 "1"=>{"day"=>"Sunday", "open_time"=>"6", "close_time"=>"6"},
 "2"=>{"day"=>"Sunday", "open_time"=>"6", "close_time"=>"6"},
 "3"=>{"day"=>"Sunday", "open_time"=>"6", "close_time"=>"6"}
}

这意味着,您的小时表应该具有属性 1、2 和 3。

【讨论】:

    猜你喜欢
    • 2011-04-03
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多