Rails check_box_tag 页面加载后保持选中状态(如果选中)
Rails check_box_tag keep checked state (if checked) after page load
我正在关注 this guide rails 中的多复选框。我使用的是 Rails 3 约定,所以我仍然使用 attr_accessible 而不是强参数。除了出现此错误外,一切似乎都正常:
undefined method `match' for []:Array
userprofile.rb 型号:
class Userprofile < ActiveRecord::Base
before_save do
self.expertise.gsub!(/[\[\]\"]/, "") if attribute_present?("interest")
end
attr_accessible :interest, :user_id, :country, :state_prov, :city
serialize :interest, Array
userprofiles_helper.rb:
module UserprofilesHelper
def checked(area)
@userprofile.interest.nil? ? false : @userprofile.interest.match(area)
end
end
_form.html.erb:
<h3>Area of Interest</h3>
<%= label_tag 'interest_physics', 'Physics' %>
<%= check_box_tag 'userprofile[interest][]', 'Physics', checked("Physics"), id: 'interest_physics' %>
<%= label_tag 'expertise_maths', 'Maths' %>
<%= check_box_tag 'userprofile[interest][]', 'Maths', checked("Maths"), id: 'interest_maths' %>
如果我删除选中的辅助方法,则复选框值不会保留。我一直在尝试修复未定义的方法 'match' 错误。或者找到另一种方法来在我编辑表单时保持选中正确的复选框值。
任何建议都会有所帮助,谢谢!
因为 Userprofile#interest
是一个数组,看起来你真的想在你的助手中使用 include?
而不是 match
。所以在 userprofiles_helper.rb:
def checked?(area)
@userprofile.interest.present? && @userprofile.interest.include?(area)
end
我正在关注 this guide rails 中的多复选框。我使用的是 Rails 3 约定,所以我仍然使用 attr_accessible 而不是强参数。除了出现此错误外,一切似乎都正常:
undefined method `match' for []:Array
userprofile.rb 型号:
class Userprofile < ActiveRecord::Base
before_save do
self.expertise.gsub!(/[\[\]\"]/, "") if attribute_present?("interest")
end
attr_accessible :interest, :user_id, :country, :state_prov, :city
serialize :interest, Array
userprofiles_helper.rb:
module UserprofilesHelper
def checked(area)
@userprofile.interest.nil? ? false : @userprofile.interest.match(area)
end
end
_form.html.erb:
<h3>Area of Interest</h3>
<%= label_tag 'interest_physics', 'Physics' %>
<%= check_box_tag 'userprofile[interest][]', 'Physics', checked("Physics"), id: 'interest_physics' %>
<%= label_tag 'expertise_maths', 'Maths' %>
<%= check_box_tag 'userprofile[interest][]', 'Maths', checked("Maths"), id: 'interest_maths' %>
如果我删除选中的辅助方法,则复选框值不会保留。我一直在尝试修复未定义的方法 'match' 错误。或者找到另一种方法来在我编辑表单时保持选中正确的复选框值。
任何建议都会有所帮助,谢谢!
因为 Userprofile#interest
是一个数组,看起来你真的想在你的助手中使用 include?
而不是 match
。所以在 userprofiles_helper.rb:
def checked?(area)
@userprofile.interest.present? && @userprofile.interest.include?(area)
end