2014-11-10 2 views
1

Так что мои рельсы приложение имеет ряд тарифов аэропортов, определенные для каждого оператора, как:Как решить NoMethodError для этого случая?

class AirportFare < ActiveRecord::Base 
    belongs_to :operator 
end 

class Operator < ActiveRecord::Base 
    has_many :airport_fares 
end 

Моих маршрутов определяются как:

resources :operators do 
    resources :airport_fares 
end 

И следующий мой airport_fares_controller:

class AirportFaresController < ApplicationController 
    before_action :set_airport_fare, only: [:show, :edit, :update, :destroy] 
    before_action :set_operator 

    # GET /airport_fares 
    # GET /airport_fares.json 
    def index 
    @operator = Operator.find(params[:operator_id]) 
    @airport_fares = Operator.find(params[:operator_id]).airport_fares 
    end 

    # GET /airport_fares/1 
    # GET /airport_fares/1.json 
    def show 
    end 

    # GET /airport_fares/new 
    def new 
    @airport_fare = Operator.find(params[:operator_id]).airport_fares.build 
    end 

    # GET /airport_fares/1/edit 
    def edit 
    end 

    # POST /airport_fares 
    # POST /airport_fares.json 
    def create 
    @airport_fare = Operator.find(params[:operator_id]).airport_fares.build(airport_fare_params) 

    respond_to do |format| 
     if @airport_fare.save 
     format.html { redirect_to @airport_fare, notice: 'Airport fare was successfully created.' } 
     format.json { render :show, status: :created, location: @airport_fare } 
     else 
     format.html { render :new } 
     format.json { render json: @airport_fare.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # PATCH/PUT /airport_fares/1 
    # PATCH/PUT /airport_fares/1.json 
    def update 
    respond_to do |format| 
     if @airport_fare.update(airport_fare_params) 
     format.html { redirect_to @airport_fare, notice: 'Airport fare was successfully updated.' } 
     format.json { render :show, status: :ok, location: @airport_fare } 
     else 
     format.html { render :edit } 
     format.json { render json: @airport_fare.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    # DELETE /airport_fares/1 
    # DELETE /airport_fares/1.json 
    def destroy 
    @airport_fare.destroy 
    respond_to do |format| 
     format.html { redirect_to operator_airport_fares_path(operator_id: @operator.id), notice: 'Airport fare was successfully destroyed.' } 
     format.json { head :no_content } 
    end 
    end 

    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_operator 
     @operator = Operator.find(params[:operator_id]) 
    end 

    def set_airport_fare 
     @airport_fare = AirportFare.find(params[:id]) 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def airport_fare_params 
     params.require(:airport_fare).permit(:cabcat, :triptype, :triptime, :basedist, :basehr, :basechrg, :ratepkm, :waitingbtime, :waitingchrg, :notes, :operator_id) 
    end 
end 

My db schema говорит:

create_table "airport_fares", force: true do |t| 
    t.string "cabcat" 
    t.string "triptype" 
    t.string "triptime" 
    t.decimal "basedist",  precision: 8, scale: 2 
    t.integer "basehr" 
    t.decimal "basechrg",  precision: 8, scale: 2 
    t.decimal "ratepkm",  precision: 8, scale: 2 
    t.integer "waitingbtime" 
    t.decimal "waitingchrg", precision: 8, scale: 2 
    t.text  "notes" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.integer "operator_id" 
    end 

Проблема в том, что я пытаюсь это сделать в моей консоли: AirportFare.first.operator. Это приводит к ошибке:

NoMethodError: undefined method 'operator' for #<AirportFare>. 

Где проблема?

+0

': attr_accessor' [issue] (http://stackoverflow.com/questions/4370960/what-is-attr-accessor-in-ruby)? – mudasobwa

+0

Вы назначили оператора AirporeFare перед тем, как попробовать это – doz87

+0

Вы уверены, что перезапустили консоль после написания кода ассоциации в файлах моделей? –

ответ

1

В новой акции вы должны сделать:

def new 
    @operator = Operator.find(params[:operator_id]) 
    @airprot_fare = AirportFare.new 
end 

в форму:

<%= form_for [@operator, @airport_fare] do |f| %> 

Это должно работать.

+0

Это имеет смысл – RSB

+0

Спасибо Shatabdi .... это работает! –

0

Должно быть operator.first.airport_fares. Как у вас есть has_many отношения на операторов

+0

Thats fine Hemail ... но как мне создать форму для добавления нового ArportFare? Я использую: <% = form_for [@ airport_fare.operator, @airport_fare] do | f | %>, но это не работает, из-за проблемы, описанной выше ... –

+1

@Hemali Это не совсем правильно. это отношения, это не один из способов. Вы можете получить к нему доступ в любом случае (например, AirportFare.operator или Operator.AirportFares), единственное отличие заключается в плюрализации для множества ассоциаций – doz87

+1

@Hemali Вам не нужно 'first' с' find' – RSB

Смежные вопросы