我有Street
模型和Map
模型。他们彼此无关。我想使用Map
模型帮助选择Leaflet地图的地图(可能是错误的方式,但我试图为地图设置不透明度滑块,现有的叠加层假设点或线)。
所以我想在maps
(streets
和show
)的页面上显示来自edit
的表格(所有可用地图的列表)。
streets_controller.rb
:
class StreetsController < ApplicationController
before_action :set_street, only: [:show, :edit, :update, :destroy]
# Trying to make list of maps available to streets views for working with the map
@maps = Map.all
# GET /streets
# GET /streets.json
def index
@streets = Street.all # Without pagination. Added Listing 10.46
# @streets = Street.paginate(page: params[:page]) # With pagination
end
# GET /streets/1
# GET /streets/1.json
def show
gon.streetExtentArray = @street.extent_array
end
# GET /streets/new
def new
@street = Street.new
gon.streetExtentArray = @street.extent_array
end
# GET /streets/1/edit
def edit
gon.streetExtentArray = @street.extent_array
end
# POST /streets
# POST /streets.json
def create
@street = Street.new(street_params)
respond_to do |format|
if @street.save
format.html { redirect_to @street, notice: 'Street was successfully created.' }
format.json { render :show, status: :created, location: @street }
else
format.html { render :new }
format.json { render json: @street.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /streets/1
# PATCH/PUT /streets/1.json
def update
respond_to do |format|
if @street.update(street_params)
format.html { redirect_to @street, notice: 'Street was successfully updated.' }
format.json { render :show, status: :ok, location: @street }
else
format.html { render :edit }
format.json { render json: @street.errors, status: :unprocessable_entity }
end
end
end
# DELETE /streets/1
# DELETE /streets/1.json
def destroy
@street.destroy
respond_to do |format|
format.html { redirect_to streets_url, notice: 'Street was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_street
@street = Street.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def street_params
params.require(:street).permit(:prevName, :currentName, :dateEarliest, :dateLatest, :where, :extent_json, :extent, :extent_array, :numBlocks, :ref1, :ref2, :ref3, :notes)
end
end
在streets/show.html.erb
<div class="col-1">
<% @maps.each do |map| %>
<p><%= map.name %></p>
<% end %>
</div>
其中name
是Map
模型中的字段。
错误:
未定义的方法`每个&#39;为零:NilClass。
这是基本的Rails,但显然超出了我的有限知识。谢谢你的建议。
答案 0 :(得分:2)
问题是您没有在控制器中的任何操作中设置@maps = Map.all
,因此它在您的视图中不可用,因此@maps
为nil
。
要解决此问题,请将该行移至show
操作:
def show
@maps = Map.all
gon.streetExtentArray = @street.extent_array
end