2016-07-06 30 views
0

创业板:怎么做Rails的CRUD无脚手架命令

gem 'simple_form', '~> 3.2', '>= 3.2.1' 
gem 'haml', '~> 4.0', '>= 4.0.7' 

在型号:

ActiveRecord::Schema.define(version: 20160706040748) do 
    create_table "jobs", force: :cascade do |t| 
    t.string "title" 
    t.text  "description" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 
end 

在控制器:

class JobController < ApplicationController 

before_action :find_job, only: [:show, :edit, :update, :destroy] 

    def index 
    end 

    def show 
    end 

    def new 
    @job = Job.new 
    end 

    def create 
    @job = Job.new(jobs_params) 
    if @job.save 
     redirect_to @job 
    else 
     render "New" 
    end 
    end 

    def edit 
    end 

    def update 
    end 

    def destroy 
    end 

    private 

    def jobs_params 
    params.require(:job).permit(:title, :description) 
    end 

    def find_job 
    @job = Job.find(params[:id]) 
    end 

end 

在路线:

resources :job 
root 'job#index' 

在View(新):

%h1 New Job 
= render 'form' 
= link_to "Back", root_path 

在局部视图(形式):****使用simple_form宝石***

= simple_form_for(@job, html: { class: 'form-horizontal'}) do |f| 
= f.input :title, label: "Course Title" 
= f.input :description, label: "Course description" 
%br/ 
= f.button :submit 

当我与http://localhost:3000/job/new

NoMethodError in Job#new 

undefined method `jobs_path' for #<#<Class:0x007ffcf6241328>:0x007ffcfe176bc0> 

= simple_form_for(@job, html: { class: 'form-horizontal'}) do |f| 
= f.input :title, label: "Course Title" 
= f.input :description, label: "Course description" 
%br/ 
= f.button :submit 
运行

回答

1

在路线中,使用as

resources :job, as: :jobs 
root 'job#index' 

-OR-

更改为单数resources =>resource

resource :job 
root 'job#index' 

见:http://guides.rubyonrails.org/routing.html#singular-resources

-OR-

指定url直接:

= simple_form_for(@job, url: job_path, html: {class: 'form-horizontal'}) do |f| 
+1

哦,我的天啊,你用这行代码保存我的一天:')我已经搜索了近一天。 – Osp

+0

@Osp不客气。考虑接受这个答案,请参阅说明:http://meta.stackexchange.com/a/5235/249307 – SoAwesomeMan