有很多通过复选框不保存值 Rails3 [英] Has Many Through Checkboxes Not Saving Values Rails3
问题描述
我已经在我的数据库中建立了一个 has_many through 关系并更改了密钥,因为我正在使用旧数据库.
I've set up a has_many through relationship in my db and changed the keys because I'm working with a legacy db.
似乎一切正常,但我无法将复选框保存到数据库中.
It all seems to be working but I cannot get the checkboxes to save to the database.
我的模型如下:
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
在我的表单中,我有这个:
In my form, I have this:
<% Radgroupcheck.all.each do |group| -%>
<%= check_box_tag :groupnames, group.id, @radcheck.radgroupcheck.include?(group), :username => 'radcheck[groupname][]' -%> | <%= label_tag :groupnames, group.groupname -%>
<% end -%>
表单呈现复选框正常,我可以看到组名,但是当我点击保存时没有任何反应.
The form renders the checkboxes ok and I can see the groupnames but nothing happens when I hit save.
开发日志清晰,mysql查询日志也看不到任何东西.
The development log is clear and I can't see anything in the mysql query log either.
推荐答案
试试在你的表单中使用这个:
Try using this in your form:
<% 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
这是改编自在 Rails 3.1 项目中对我有用的内容,基于 http://railscasts.com/episodes/17-habtm-checkboxes?view=asciicast
This is adapted from what worked for me in a Rails 3.1 project, based on http://railscasts.com/episodes/17-habtm-checkboxes?view=asciicast
这篇关于有很多通过复选框不保存值 Rails3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!