我一直在這一天卡住了一天。我聽說過Rails能夠處理這樣簡單的複雜性的所有這些話題(儘管這不是/不應該是複雜的)。Rails 3 has_many通過複選框形式不(不)工作
故事:用戶可以有很多高級學位。我希望能夠通過has_many through關係創建該關聯,並在我的視圖中使用複選框。
型號:
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關係不創建。
我在這裏做錯了什麼?
你是如何解決它的? – sparkle 2013-07-03 18:52:38