繁体   English   中英

Rails has_one和belongs_to帮助

[英]Rails has_one and belongs_to help

我有两个模型:用户和商店

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

用户必须登录才能通过输入“email”和“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 = nil。 由于某种原因,它无法将current_user.id放入@ store.user_id。 任何人都能帮助检测为什么会这样? 我以为我有正确实施的关联。 谢谢

发生这种情况是因为您在@store.user_id后设置了@store.user_id

理想情况下,您应该使用关联构建器:

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

有关这些的更多信息,请参阅“关联基础知识”指南。

暂无
暂无

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

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