0
我有兩個模型,用戶和組織,它們使用賦值表具有has_many關係。當創建用戶時,我有一個嵌套的資源表單,這就創建了一個關聯的組織。但是,創建組織時,它不會將其與用戶關聯。控制器沒有創建關聯
這裏是我的相關組織控制器代碼:
def new
@organization = current_user.organizations.build
end
def create
@organization = current_user.organizations.build(params[:organization])
@organization.save
end
而且我的模型:
組織分配
class OrganizationAssignment < ActiveRecord::Base
belongs_to :user
belongs_to :organization
attr_accessible :user_id, :organization_id
end
組織:
class Organization < ActiveRecord::Base
validates :subdomain, :presence => true, :uniqueness => true
has_many :organization_assignments
has_many :people
has_many :users, :through => :organization_assignments
attr_accessible :name, :subdomain
end
用戶:
class User < ActiveRecord::Base
has_many :organization_assignments
has_many :organizations, :through => :organization_assignments
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
accepts_nested_attributes_for :organizations
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :organizations_attributes
# attr_accessible :title, :body
end
表單視圖:
= form_for @organization, :html => { :class => 'form-horizontal' } do |f|
- @organization.errors.full_messages.each do |msg|
.alert.alert-error
%h3
= pluralize(@organization.errors.count, 'error')
prohibited this user from being saved:
%ul
%li
= msg
= f.label :name
= f.text_field :name
= f.label :subdomain
= f.text_field :subdomain
.form-actions
= f.submit nil, :class => 'btn btn-primary'
= link_to t('.cancel', :default => t("helpers.links.cancel")), organizations_path, :class => 'btn'
我能夠在控制檯事後精細組織聯繫起來,所以我敢肯定的關係在模型中正確設置。還有什麼我失蹤?
謝謝,這是有效的,而且是有道理的。有一件事,我必須將Organization.build更改爲Organization.create,並刪除.save行。 – Asherlc 2012-07-28 01:35:58
您如何選擇和修改您提及的方式?我假設你用上面的第二個代碼塊去了;我相信我的第一個代碼塊中的代碼按原樣運行。 – deefour 2012-07-28 01:38:47
我實際上使用了第一個博客 - 它給了我一個錯誤。不記得錯誤的錯誤。 – Asherlc 2012-07-28 02:03:20