2016-07-06 1 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' 
部分ビュー(フォーム)で

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

::ビュー(新しい)で

simple_form宝石***を使う****私は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 
でそれを実行し
= 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' 
単数 resources => resourceから

-OR-

変更:

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