Has_many通过复选框不保存值Rails 3

时间:2011-11-26 13:27:22

标签: ruby-on-rails ruby ruby-on-rails-3

我在我的数据库中建立了一个has_many through关系并更改了密钥,因为我正在使用遗留数据库。

这一切似乎都在起作用,但我无法将复选框保存到数据库中。

我的模型如下:

class Radcheck < ActiveRecord::Base
  set_table_name 'radcheck'
  attr_accessible :attribute_name, :username, :value, :op, :groupname
  belongs_to :raduser

  has_many :radusergroup, :dependent => :destroy, :primary_key => :username, :foreign_key => :groupname
  has_many :radgroupcheck, :through => :radusergroup
end


class Radgroupcheck < ActiveRecord::Base
  set_table_name 'radgroupcheck'
  has_many :radusergroup, :dependent => :destroy#, :primary_key => :groupname, :foreign_key => :username
  has_many :radcheck, :through => :radusergroup
end


class Radusergroup < ActiveRecord::Base
  belongs_to :radcheck, :foreign_key => 'groupname', :primary_key => 'username'
  belongs_to :radgroupcheck, :foreign_key => 'username', :primary_key => 'groupname'
end

在我的表格中,我有这个:

<% Radgroupcheck.all.each do |group| -%>
  <%= check_box_tag :groupnames, group.id, @radcheck.radgroupcheck.include?(group), :username => 'radcheck[groupname][]' -%> | <%= label_tag :groupnames, group.groupname -%>
<% end -%>

表单呈现复选框,我可以看到组名,但是当我点击保存时没有任何反应。

开发日志很清楚,我在mysql查询日志中也看不到任何内容。

1 个答案:

答案 0 :(得分:4)

尝试在表单中使用此功能:

<% Radgroupcheck.all.each do |group| -%>
  <%= check_box_tag "radcheck[radgroupcheck_ids][]", radgroupcheck.id, @radcheck.radgroupchecks.include?(radgroupcheck), :id => "radcheck_radgroupcheck_id_#{radgroupcheck.id}" -%>
  <%= label_tag "radcheck[radgroupcheck_ids][]", radgroupcheck.name, :for => "radcheck_radgroupcheck_id_#{radgroupcheck.id}" -%>
<% end %>

在你的控制器中:

def create
  params[:radcheck][:radgroupcheck_ids] ||= []
  @radcheck = Radcheck.new(params[:radcheck])

  # rest of your controller logic
end

这是基于http://railscasts.com/episodes/17-habtm-checkboxes?view=asciicast

改编自Rails 3.1项目中对我有用的内容