[英]Rails 3 has_many through checkbox form doesn't (does not) work
我已經堅持了一天。 我已經聽說過所有有關Rails能夠處理這樣的簡單復雜性的談話(盡管這不是(或應該不是很復雜))。
故事:用戶可以擁有許多高級學位。 我希望能夠使用has_many通過關系創建此關聯,並在我的視圖中使用復選框。
楷模:
class User < ActiveRecord::Base
has_many :user_degree_lists
has_many :degrees, :through => :user_degree_lists, :source => :advanced_degree, :dependent => :destroy
end
class AdvancedDegree < ActiveRecord::Base
attr_accessible :value, :description
has_many :user_degree_lists
end
class UserDegreeList < ActiveRecord::Base
belongs_to :user
belongs_to :advanced_degree
end
ActiveRecord:
class CreateUserDegreeLists < ActiveRecord::Migration
def self.up
create_table :user_degree_lists do |t|
t.integer :user_id
t.integer :advanced_degree_id
t.timestamps
end
add_index :user_degree_lists, :user_id
add_index :user_degree_lists, :advanced_degree_id
add_index :user_degree_lists, [:user_id, :advanced_degree_id], :unique => true
end
def self.down
drop_table :user_degree_lists
end
end
視圖:
<%= form_for(@user, :html => {:autocomplete => 'off', :id => "sign_up_user" }) do |f| %>
...
<% for advanced_degree in AdvancedDegree.find(:all)%>
<%= check_box_tag "user[advanced_degree_ids][]", advanced_degree.id, @user.degrees.include? (advanced_degree.id) %>
<%= f.label :advanced_degrees, advanced_degree.description %>
...
<% end %>
提交表單后,將更新所有用戶字段,但不會創建:user_degree_lists關系。
我在這里做錯了什么?
不知道您是否已經解決了這個問題,但是我發現了一件事情:班級用戶難道不應該擁有“ has_many:advanced_degrees”和“ has_many:degrees”嗎? 可能想嘗試在沒有源代碼的情況下嘗試(除非您正在嘗試某種多態的東西),這就是我做類似事情的方式。
1)因為這是一個聯接表,所以我將“ UserDegreeList”重命名為“ UserDegree”。
2)“ AdvancedDegree.find(:all)”可以是“ AdvancedDegree.all”。
3)我同意之前的評論,應將其重命名為“ has_many:advanced_degrees”
4)要解決此問題,請嘗試將其添加到用戶:
accepts_nested_attributes_for :advanced_degrees, :allow_destroy => true, :reject_if => :all_blank
您需要確保attr_accessible具有您在復選框中設置的attr。
class Zone < ActiveRecord::Base
attr_accessible :name, :active, :user_ids
has_many :user_zones
has_many :users, :through => :user_zones
end
class User < ActiveRecord::Base
attr_accessible :name, :zone_ids
has_many :user_zones
has_many :zones, :through => :user_zones
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.