0

我有两个要关联的模型。我有拥有许多工作的用户。我在每个模型中设置了关联,并在工作模型中添加了一个 foreign_id。当用户填写表单发布工作时,user_id 返回 nil。我究竟做错了什么?我需要在我的创建操作中添加任何内容吗?我的表单中是否应该为foreign_key添加一个字段?这是我到目前为止所拥有的。谢谢。

create_table "jobs", :force => true do |t|
    t.string   "category"
    t.string   "title"
    t.text     "description"
    t.string   "location"
    t.integer  "needed"
    t.decimal  "pay"
    t.string   "how"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
    t.decimal  "hours"
    t.date     "start_date"
    t.integer  "user_id"
  end


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
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                             :null => false
    t.datetime "updated_at",                             :null => false
  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

class Job < ActiveRecord::Base
  belongs_to :user
  attr_accessible :category, :description, :how, :location, :needed, :pay, :start_date, :title,:hours
   validates :category, :title, :description, :how, :location, :needed,:hours, :pay,:start_date, presence: true
   validates :pay, :numericality => { :greater_than => 7.99 } 
end


class User < ActiveRecord::Base
  has_many :jobs, dependent: :destroy
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  attr_accessible :email, :password, :password_confirmation, :remember_me
  # attr_accessible :title, :body
end
4

1 回答 1

0

是的,在您的create行动中,JobsController您必须编写如下内容:

current_user.jobs.build(params[:job])

或者

@user.jobs.build(params[:job])

代替

Job.new(params[:job])
于 2013-08-19T12:41:23.680 回答