通过站点控制器写入Resident Model以自动为特定站点

时间:2015-05-04 07:43:02

标签: ruby-on-rails-4 activerecord

大家晚上!我的控制器出了问题,它正在回归undefined method居民'为nil:NilClass`当我尝试渲染页面时。

我正在尝试将新居民填充到特定网站。

我的sites_controller.rb如下所示。 - 我创建了方法site_resident来处理这个问题。 (从页面顶部开始的方法。



    class SitesController < ApplicationController
  before_action :authenticate_user!
  before_action :set_site, only: [:show, :edit, :update, :destroy]

  # GET /sites
  # GET /sites.json
  def index
    @sites = Site.all
  end

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

  def site_resident
    @resident = @site.residents.new
  end

  # GET /sites/new
  def new
    @site = Site.new
  end

  # GET /sites/1/edit
  def edit
  end

  # POST /sites
  # POST /sites.json
  def create
    @site = Site.new(site_params)

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

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

  # DELETE /sites/1
  # DELETE /sites/1.json
  def destroy
    @site.destroy
    respond_to do |format|
      format.html { redirect_to sites_url, notice: 'Site was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_site
      @site = Site.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def site_params
      params.require(:site).permit(:call_sign, :address, :unit_number, :city, :prov, :postal_code, :ec1_n, :ec1_t, :ec1_t, :ec2_n, :ec2_t, :ec2_e, :ec3_n, :ec3_t, :ec3_e, :lat, :lng)
    end
end
&#13;
&#13;
&#13;

我的routes.rb文件如下所示:

&#13;
&#13;
Rails.application.routes.draw do
  root 'home#index'

  resources :residents
   
  resources :sites do
    member do
      get :site_resident
    end
  end
  
  devise_for :users
&#13;
&#13;
&#13;

我确定它的东西很小,但我似乎无法绕过它。我在这里先向您的帮助表示感谢!

1 个答案:

答案 0 :(得分:1)

您需要为:site_resident的数组添加before_action :set_site。 该行应为:

before_action :set_site, only: [:show, :edit, :update, :destroy, : site_resident]