我有幾個模型(網站和服務器),通過has_many:through與eachother相關。他們也都屬於:用戶。在我的網站/新視圖中,我創建了一個新網站,並使用嵌套的form.fields_for:servers創建了一個新的服務器。一切都按預期工作,除了最終創建的服務器沒有填充user_id。我如何確保它是?Rails的外鍵在嵌套形式爲零
我sites_controller新創建的方法:
def new
@user = current_user
@site = @user.sites.build
@servers = @user.servers.all
# let there be one server linked
@site.site_servers.build
# @user.servers.build if @user.servers.empty?
@site.servers.build(:user_id => current_user.id) if @site.servers.empty?
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @site }
end
end
def create
@site = current_user.sites.build(params[:site])
respond_to do |format|
if @site.save
flash[:notice] = 'Site was successfully created.'
format.html { redirect_to(@site) }
format.xml { render :xml => @site, :status => :created, :location => @site }
else
format.html { render :action => "new" }
format.xml { render :xml => @site.errors, :status => :unprocessable_entity }
end
end
end
如果您發現該註釋行,這些事情我試過,沒有工作。
型號:
class User < ActiveRecord::Base
acts_as_authentic
has_many :sites
has_many :servers
end
class Site < ActiveRecord::Base
belongs_to :user
has_many :site_servers
has_many :servers, :through => :site_servers
accepts_nested_attributes_for :site_servers, :allow_destroy => true
accepts_nested_attributes_for :servers, :allow_destroy => true
validates_presence_of :name, :on => :create, :message => "Name is required"
end
class Server < ActiveRecord::Base
attr_encrypted :password, :key => '393b79433f616f445f652a752d', :attribute => 'crypted_password'
belongs_to :user
has_many :site_servers
has_many :sites, :through => :site_servers
validates_presence_of :url, :on => :create, :message => "URL is required."
validates_presence_of :username, :on => :create, :message => "Username is required."
validates_presence_of :password, :on => :create, :message => "Password is required."
def name
username + "@" + url
end
def to_s
name
end
end
class SiteServer < ActiveRecord::Base
belongs_to :site
belongs_to :server
has_one :user, :through => :site
end
而且這裏是我的架構:
ActiveRecord::Schema.define(:version => 20091203045550) do
create_table "servers", :force => true do |t|
t.string "url"
t.string "username"
t.string "crypted_password"
t.integer "port"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "site_servers", :force => true do |t|
t.integer "site_id"
t.integer "server_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "sites", :force => true do |t|
t.string "name"
t.string "url"
t.string "path"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", :force => true do |t|
t.string "username"
t.string "email"
t.string "crypted_password"
t.string "password_salt"
t.string "persistence_token"
t.datetime "created_at"
t.datetime "updated_at"
end
end
粘貼您的模型。 – bensie 2009-12-14 02:47:15