如果问题的标题有点令人困惑,我很抱歉,但我真的很难用更好的语言表达出来。
我正在尝试访问控制器中fields_for
提交中的单个属性。
我的表格是这样的:
= form_for @match, :url => matches_search_path, remote: true do |f|
= f.select :sport_id, options_from_collection_for_select(Sport.all, "id", "name"), {:prompt => "Select Sport..."}, class: "form-control"
= f.fields_for @match.build_location do |g|
= g.text_field :zip, :class => "form-control", :value => @user.location.zip, :placeholder => "Zip"
= f.text_field :max_players, :class => "form-control", :placeholder => "Player Limit (in total)"
= f.submit "Search", :class => "btn btn-info"
和MatchesController一样:
class MatchesController < ApplicationController
before_filter :current_user
def index
@match = Match.new
@user = current_user
end
def new
@match = Match.new
@match.build_location
end
def create
@user = User.find(session[:user_id])
@match = @user.matches.build(match_params)
if @match.save
redirect_to :root, :notice => "Match created."
else
render :new, :alert => "Failed to create match."
end
end
def search
# Get all matches for the searched sport
@results = Match.sport_id(match_params[:sport_id])
#This is where the problem is:
@coordinates = Geocoder.coordinates(match_params[:location][:zip])
@results = @results.select {|result| result.location.distance_from(@coordinates)}
respond_to :js
end
private def match_params
params.require(:match).permit(:sport_id, :name, :description, :choose_teams, :keeping_score, :max_players, :time, location_attributes: [:address, :city, :state, :zip])
end
end
路线很好:
# Matches
resources :matches
post 'matches/search', as: :matches_search
表单向MatchesController
中的search
方法提交了一个ajax调用。问题是我得到了:
undefined method `[]' for nil:NilClass
在线上
@coordinates = Geocoder.coordinates(match_params[:location][:zip])
我试着在谷歌上搜索这个问题,但我发现最接近这个问题的是这里,当试图访问"哈希中的哈希"时,要使用:
params[:outer_hash][:inner_hash]
当我使用CCD_ 4或CCD_。
我验证了表格中的信息是否发送到控制器。我只是似乎无法正确访问它。
我到底做错了什么?
编辑:
以下是表格的回复:(我屏蔽了真实性_token)
{"utf8"=>"✓", "authenticity_token"=>"XXXXXXXXXXXXXXXXXXXXXXX",
"match"=>{"sport_id"=>"4",
"location"=>{"zip"=>"11211"},
"max_players"=>""},
"commit"=>"Search"}
我认为发生的情况是您的match_params
不允许location
参数进入(我猜是匹配的has_one
位置)。更改线路:
@coordinates = Geocoder.coordinates(match_params[:location][:zip])
至:
@coordinates = Geocoder.coordinates(params[:match][:location][:zip])
或者更好的是,将您的match_params
更改为:
params.require(:match).permit(:sport_id, :name, :description, :choose_teams, :keeping_score, :max_players, :time, location: [:address, :city, :state, :zip])