Ruby on Rails:循环中的批量分配? [英] Ruby on Rails: Mass-Assignment on iteration in loop?

查看:97
本文介绍了Ruby on Rails:循环中的批量分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到批量分配错误.

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

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

These numbers represent the iteration in this loop:

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

这是我的模型:

attr_accessible :day, :open_time, :close_time

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

I'm trying to create an array like this:

"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"}
}

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

And I'm trying to save each iteration in a new row into the database

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

如何解决迭代质量分配?还是我做错了?

How do I fix the iteration mass-assignment? or am I doing this all wrong?

谢谢!

推荐答案

从哈希中,Active Record假定"1","2"和"3"是模型的列名或属性,并且未指定用于访问列的attr_accessible选项,它将抛出mass-assignment error.否则,您需要创建一个哈希,如下所示:

From the hash, Active Record assumes that '1', '2' and '3' are column names OR attributes of the Model and as you have not specified attr_accessible option for the accessing columns, it is throwing mass-assignment error. Otherwise you need to create a hash as follows:

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

希望它会有所帮助:)

这篇关于Ruby on Rails:循环中的批量分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆