2011-04-03 195 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