belongs_to和user(设计)的问题

时间:2015-01-30 14:59:31

标签: ruby-on-rails devise belongs-to

我是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
&#13;
&#13;
&#13;

user.rb模型

&#13;
&#13;
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
&#13;
&#13;
&#13;

Timesheet.rb模型

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

提前致谢。

1 个答案:

答案 0 :(得分:0)

它会保持为null因为你没有在timesheetsController中使用它,你的创建动作应该是这样的:

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

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