【问题标题】:Single checkbox to update multiple attributes Rails 4单个复选框更新多个属性 Rails 4
【发布时间】: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(),所以数据库中的记录没有更新。
  • 对不起,不;这不是一个完整的更新操作。我只包括了相关的位。但是更新操作有效,我可以编辑模型中除此之外的所有内容。

标签: ruby-on-rails checkbox


【解决方案1】:

update 没有保存您的手动(超出参数)调整。

你要么只需要操作参数,比如

if checkbox_params[:weekday_closed_checkbox] == "checked"
    params[:restaurant].merge { 
      weekday_open_at: nil,
      weekday_close_at: nil }
end

或者只是保存

@restaurant.attributes = restaurant_params
if @restaurant.save
    redirect_to @restaurant
else
    render 'edit'
end

但最好在模型中使用before_save。

【讨论】:

    【解决方案2】:

    我会这样做:

    # _form.html.erb
    <%= check_box_tag "restaurant[make_everything_nil]", "checked" %>
    

    然后你得到params[restaurant][:make_everything_nil]。在您的控制器中,您可以检查它的值:

    # xxx_controller.rb
    def update
      if params[restaurant][:make_everything_nil] == true
        # set all the values here
      end
    
      # the rest of logic here
    end
    

    用更合理的名称替换操作。我只是举个例子。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多