belongs_to 和用户问题(设计)

Issue with belongs_to and user (devise)

我是 RoR 的新手,我想开发一个应用程序,但我对 belongs_to 协会有疑问。我正在使用 devise 对我的用户进行身份验证,我有一个名为 timesheet 的对象,我遵循了几个教程并阅读了很多论坛,但不幸的是 user_id 仍然是 null在我的数据库中,所以我不知道问题出在哪里。

如果你能告诉我如何修复它,任何可以帮助我的链接,那就太好了。

Schema.rb:

ActiveRecord::Schema.define(version: 20150128160116) do

  create_table "timesheets", force: true do |t|
    t.date     "date"
    t.time     "working_start_time"
    t.time     "working_end_time"
    t.integer  "breaks"
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "timesheets", ["user_id"], name: "index_timesheets_on_user_id"

  create_table "users", force: true do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.integer  "current_sign_in_ip"
    t.integer  "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end

timesheets_controller.rb

class TimesheetsController < ApplicationController
 layout 'application'
 
def show
  @timesheet=Timesheet.find(params[:id])
end
 
def index
  @timesheet = Timesheet.all
end
  

def new
    @timesheet = Timesheet.new
end

def create
       @timesheet = Timesheet.create(timesheet_params)
       redirect_to new_timesheet_path
end

  def edit
    @timesheet=Timesheet.find(params[:id])
  end
  
    def update
    @timesheet = Timesheet.find(params[:id])
    @timesheet.update_attributes(timesheet_params)
  redirect_to student_table_path
end

user.rb 型号

class User < ActiveRecord::Base

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
has_many :timesheets
end

Timesheet.rb 型号

class Timesheet < ActiveRecord::Base
belongs_to :user
validates :user_id, :presence => true
end

提前致谢。

它将保持为空,因为您没有在 timesheetsController 中使用它,您的创建操作应该是这样的:

def create
  @timesheet = current_user.timesheets.build(timesheet_params)
  redirect_to new_timesheet_path
end

您必须使用 build 方法来引用 current_user,因此时间表将在 user_id 字段中包含 current_user。