简体   繁体   English

Rails has_one和belongs_to帮助

[英]Rails has_one and belongs_to help

I have two models: User and Store 我有两个模型:用户和商店

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

User must login in order to sign up a store by inputting "email" and "store_name". 用户必须登录才能通过输入“email”和“store_name”来注册商店。 create from stores_controller looks like this: 从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

In ApplicationsController 在ApplicationsController中

def current_user
    @current_user ||= user_from_remember_token
end

However, when I check in the database, @store.user_id = nil. 但是,当我签入数据库时​​,@ store.user_id = nil。 For some reason, it's not able to put in current_user.id into @store.user_id. 由于某种原因,它无法将current_user.id放入@ store.user_id。 Anybody able to help in detecting why this might be? 任何人都能帮助检测为什么会这样? I thought I had associations correctly implemented. 我以为我有正确实施的关联。 Thanks 谢谢

This is happening because you're setting the @store.user_id AFTER saving it. 发生这种情况是因为您在@store.user_id后设置了@store.user_id

Ideally, you should be using the association builder for this: 理想情况下,您应该使用关联构建器:

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

More information about these can be found in the "Association Basics" guide. 有关这些的更多信息,请参阅“关联基础知识”指南。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM