class CreateJobs < ActiveRecord::Migration[5.1]
def change
create_table :jobs do |t|
t.string :title
t.text :description
t.string :company
t.integer :user_id
t.integer :company_id
t.timestamps
end
end
end
class CreateCompanies < ActiveRecord::Migration[5.1]
def change
create_table :companies do |t|
t.string :c_name
t.text :c_description
t.integer:user_id
t.timestamps
end
end
end
# Models
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :companies
has_many :jobs
end
class Job < ApplicationRecord
belongs_to :user
belongs_to :category
belongs_to :company
end
class Company < ApplicationRecord
belongs_to:user
has_many:jobs
end
# Jobs controller
def show
end
def new
@job = current_user.jobs.build
end
def create
job_attrs = jobs_params.except(:company)
job_attrs[:company] = Company.find_by(id: jobs_params[:company])
@job = current_user.jobs.build(job_attrs)
if @job.save
flash[:success]= "success"
redirect_to @job
else
flash[:error]=@job.errors.full_messages
render "new"
end
end
def jobs_params
params.require(:job).permit(:title, :description, :company, :category_id, :image,:jobclosedate,:company_id)
end
这是views / jobs / _form
<%= simple_form_for(@job,validation:true ,html: { mutlipart: true, class: 'form-horizontal'}) do |f| %>
<%= f.input :title, label: "Job Title", input_html: { class: "form-control"}%>
<%= f.input :description, label: "Job Description", input_html: { class: "form-control" }%>
<%= f.input :company, label: "Your Company", input_html: { class: "form-control" }%>
<%= f.collection_select :category_id,Category.all, :id, :name, {promt: "Choose a category" }%>
当我尝试创建作业时,它将显示在views / jobs / _form.html.erb
中“公司必须存在”(job / _form不会从公司模块获取公司名称) 公司应自动填充在views / jobs / _form.html.erb中,它不会自动填充,并且公司会退出