我想要关联的两个模型。我的用户有很多工作。我在每个模型中设置关联,并将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
答案 0 :(得分:0)
是的,在create
的{{1}}行动中,您必须写下以下内容:
JobsController
或
current_user.jobs.build(params[:job])
而不是
@user.jobs.build(params[:job])