2011-04-03 79 views
0

我有兩個模式:用戶和存儲Rails的HAS_ONE和belongs_to的幫助

class Store < ActiveRecord::Base 
    belongs_to :user 

class User < ActiveRecord::Base 
    has_one :store 

Schema looks like this: 

create_table "users", :force => true do |t| 
    t.string "name" 
    t.string "email" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.string "encrypted_password" 
    t.string "salt" 
    t.boolean "admin",    :default => false 
    t.string "username" 
    t.string "billing_id" 
    end 

create_table "stores", :force => true do |t| 
    t.string "email" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.string "store_name" 
    t.integer "user_id" 
    end 

用戶必須先通過輸入「電子郵件」和「STORE_NAME」註冊商店登錄。從stores_controller看起來像這樣創建:

def create 

    @store = Store.new(params[:store]) 
    if @store.save 
    @store.user_id = current_user.id 
    flash[:success] = "this store has been created" 
    redirect_to @store 
    else 
    @title = "store sign up" 
    render 'new' 
    end 
end 

在ApplicationsController

def current_user 
    @current_user ||= user_from_remember_token 
end 

然而,當我在數據庫中,@ store.user_id =零檢查。出於某種原因,它無法將current_user.id放入@ store.user_id中。任何人都可以幫助檢測這可能是爲什麼?我認爲我有正確實施的關聯。謝謝

回答

2

發生這種情況是因爲您在保存後設置@store.user_id

理想情況下,你應該使用關聯建設者這樣的:

這些
def new 
    @store = @current_user.store.build(params[:store]) 

更多信息可以在"Association Basics"指南中找到。

+0

啊...非常感謝Ryan – railslearner 2011-04-03 20:35:20