【问题标题】:Rails Simple_Form Multiple Select CheckboxesRails Simple_Form 多选复选框
【发布时间】:2014-09-14 21:19:10
【问题描述】:

我是 Rails 新手,在 Simple_Form、Devise 和复选框方面遇到了一些问题。

我在我的设计模型中添加了一些额外的列,包括我希望用户勾选一个或多个复选框的列。类似这样:

经营地区:[]英格兰[]威尔士[]苏格兰

一切都很好,但是当我选择多个区域然后保存时,选择不会保存到数据库中。


这是我的查看代码 [app/views/devise/registrations/edit.html.erb]:

<%= simple_form_for(resource, html: { class: 'form-horizontal'}, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f| %>

<%= f.input :areas, :as => :check_boxes, :collection => ["England", "Wales", "Scotland", "Northern Ireland"] %>

<% end %>

这是我的 ApplicationController 代码 [app/controllers/application_controller.rb]:

class ApplicationController < ActionController::Base
protect_from_forgery with: :exception

before_filter :configure_permitted_parameters, if: :devise_controller?

protected

 def configure_permitted_parameters
  devise_parameter_sanitizer.for(:sign_up) << :areas
  devise_parameter_sanitizer.for(:account_update) << :areas
 end
end

我确定我遗漏了一些明显的东西,但我已经在谷歌上搜索了几个小时,但没有运气。

任何帮助将不胜感激!


编辑:

抱歉。下面是 Devise(实际上命名为 'providers')表的方案:

create_table "providers", force: true do |t|
  t.string   "email",                  default: "", null: false
  t.string   "encrypted_password",     default: "", null: false
  t.string   "reset_password_token"
  t.datetime "reset_password_sent_at"
  t.datetime "remember_created_at"
  t.integer  "sign_in_count",          default: 0,  null: false
  t.datetime "current_sign_in_at"
  t.datetime "last_sign_in_at"
  t.string   "current_sign_in_ip"
  t.string   "last_sign_in_ip"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "first_name"
  t.string   "last_name"
  t.string   "organisation"
  t.string   "street"
  t.string   "city"
  t.string   "county"
  t.string   "postcode"
  t.string   "areas"
  t.string   "methods"
end

add_index "providers", ["email"], name: "index_providers_on_email", unique: true
add_index "providers", ["reset_password_token"], name: "index_providers_on_reset_password_token", unique: true

【问题讨论】:

  • 您提供的信息太少。你的数据库架构是什么(意思是数据库中的区域是如何表示的)?
  • areas 是一个关联吗?
  • @Lucas -- 抱歉。我已更新我的问题以包含架构。
  • @kobaltz 不,areas 不是关联。我希望只在视图代码中包含复选框选项(如上)。

标签: ruby-on-rails checkbox devise simple-form-for


【解决方案1】:

保存区域的方法有很多,

1) 最好的方法是创建名为 area 的新模型并与用户建立多对多关联。 check。这是用户有许多项目关联的基本应用程序。

2) 如果您不想创建单独的区域模型,则可以将区域存储在列用户之一中。要么你可以serialize 专栏。在这里你可以以arr或hash形式存储数据

3) 在用户过滤器之前添加,在保存用户之前,加入区域并保存为字符串。

【讨论】:

  • 嗨@bunty。感谢您的答复。我认为(1)可能是我必须走的路。关于 (2) 和 (3),我是否必须为 Devise 创建自己的控制器 similar to this solution
  • 不需要。设计将在创建数据时以序列化格式保存您的区域。对于(3),您需要在用户模型中创建 before save 方法,您可以在其中传递区域数组,用逗号连接并将其设置为区域字段。
  • 原谅我——我对 Rails 很陌生。你介意给我一些模型的演示代码吗?非常感谢您的支持。
  • 嗨..你可以参考github.com/rohineematale/demo。在 user.rb 文件中,我们正在设置区域。当你想访问用户的区域时,你可以使用用户的城市方法来获取它。如果您有任何问题,请告诉我。
  • 非常感谢您抽出宝贵时间来做这件事!这对我来说非常宝贵。
猜你喜欢
  • 2011-05-06
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
相关资源
最近更新 更多