不确定原因,但是当我将这个新行添加到我的团队视图中时,我将未定义的方法“空”?错误
<div class="field">
<%= f.label :field_id %><br>
<%= f.select :field_id, @fields, prompt: "select a field" %>
</div>
以下是团队和领域的模型
class Team < ActiveRecord::Base
has_many :users
belongs_to :field
end
class Field < ActiveRecord::Base
has_many :teams
end
我必须将field_id迁移到team表中,这是
class AddFieldIdToTeams < ActiveRecord::Migration
def change
add_column :teams, :field_id, :integer
end
end
截至目前,我可以访问localhost:3000 / fields并创建一个包含名称和位置设置的新字段。当我去localhost:3000 / teams / new时发生错误。我正在尝试获取字段的下拉菜单,这样当您创建团队时,它将与团队将要播放的字段相关联。如果需要更多信息,请告诉我。感谢
编辑添加我的字段控制器
class FieldsController < ApplicationController
before_action :set_field, only: [:show, :edit, :update, :destroy]
# GET /fields
# GET /fields.json
def index
@fields = Field.all
end
# GET /fields/1
# GET /fields/1.json
def show
end
# GET /fields/new
def new
@field = Field.new
end
# GET /fields/1/edit
def edit
end
# POST /fields
# POST /fields.json
def create
@field = Field.new(field_params)
respond_to do |format|
if @field.save
format.html { redirect_to @field, notice: 'Field was successfully created.' }
format.json { render action: 'show', status: :created, location: @field }
else
format.html { render action: 'new' }
format.json { render json: @field.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /fields/1
# PATCH/PUT /fields/1.json
def update
respond_to do |format|
if @field.update(field_params)
format.html { redirect_to @field, notice: 'Field was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @field.errors, status: :unprocessable_entity }
end
end
end
# DELETE /fields/1
# DELETE /fields/1.json
def destroy
@field.destroy
respond_to do |format|
format.html { redirect_to fields_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_field
@field = Field.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def field_params
params.require(:field).permit(:name, :location)
end
end
答案 0 :(得分:3)
@fields应该在你的控制器中
@fields = Field.all
表格
<%= f.select :field_id, options_from_collection_for_select(@fields, "id", "name"),
:prompt => "Select field" %>
将“name”替换为您希望用户在下拉菜单中选择值时看到的字段模型中的值
替代方案可能是这不需要@fields变量。
<%= f.select :field_id, Field.find(:all).collect {|f| [ "#{f.name}", f.id ] } %>
再次改变f.name,就像我之前的例子一样
答案 1 :(得分:1)
您没有在团队控制器的新操作中设置@fields变量