【发布时间】:2014-08-03 01:48:24
【问题描述】:
在 Rails 应用程序上工作。我希望我的编辑视图中的单个复选框字段在选中时将多个属性设置为 nil。大多数人似乎有相反的问题:他们希望多个复选框字段保存到一个属性。
我的编辑表单如下所示:
<%= hidden_field_tag "restaurant[weekday_closed_checkbox]", nil %>
<%= check_box_tag "restaurant[weekday_closed_checkbox]", "checked" %>
Weekday_closed_checkbox 是一个虚拟属性。它不会保存到数据库中。为了适应这种情况,我的 Restaurant 控制器如下所示:
def update
@restaurant = Restaurant.find(params[:id])
if checkbox_params[:weekday_closed_checkbox] == "checked"
@restaurant.weekday_open_at = nil
@restaurant.weekday_close_at = nil
end
if @restaurant.update(restaurant_params)
redirect_to @restaurant
else
render 'edit'
end
end
# . . .
private
def restaurant_params
params.require(:restaurant).permit(:id, :name, :description, ....)
end
def checkbox_params
params.require(:restaurant).permit(:weekday_closed_checkbox)
end
end
我的餐厅模型如下所示:
attr_accessor :weekday_closed_checkbox
当编辑视图呈现并且我选中复选框并提交时,参数如下所示:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"DNq3nbGLgPTcvdG3KF8mkyJxm3i0MlQs6TjBd6ylJHQ=", "restaurant"=>{"name"=>"Name", "description"=>"World's best restaurant", . . . "weekday_closed_checkbox"=>"checked"}
但 nil 值不会保存到数据库中。
问题不在于更新操作;其他字段可以毫无问题地编辑和保存。此外,当我只使用多个复选框将属性设置为 nil 时,问题就消失了。无法弄清楚出了什么问题!
【问题讨论】:
-
这是一个完整的
update操作?因为我在记录中看不到save(),所以数据库中的记录没有更新。 -
对不起,不;这不是一个完整的更新操作。我只包括了相关的位。但是更新操作有效,我可以编辑模型中除此之外的所有内容。