【问题标题】:How to insert my association id into simple form for如何将我的关联 ID 插入简单的形式
【发布时间】:2019-09-10 13:22:20
【问题描述】:

我有一个模型属于不同的模型(游戏属于字段和组织者),但是当我填写表单创建游戏时,我的创建方法没有赶上字段引用

class Game < ApplicationRecord
 belongs_to :organiser
 belongs_to :field
end

class Organiser < ApplicationRecord
 has_many :games, dependent: :destroy
end

class Field < ApplicationRecord
 has_many :games, dependent: :destroy
end

控制器

class GamesController < ApplicationController
 before_action :set_game, only: [:show, :edit, :update, :destroy]

 def new
  @organiser = Organiser.find(params[:organiser_id])
  @game = Game.new
 end

 def create
  @game = Game.new(game_params)
  organiser_id = current_organiser.id
  @organiser = Organiser.find(organiser_id)
  @game.organiser = @organiser
  @game.save
  redirect_to organiser_games_path(@organiser)
 end

 def edit
  organiser_id = current_organiser.id
  @organiser = Organiser.find(params[:organiser_id])
 end

 def update
  organiser_id = current_organiser.id
  @organiser = Organiser.find(organiser_id)
  @game.update(game_params)
  redirect_to organiser_games_path(@organiser)
end

private
def game_params
 params.require(:game).permit(:field_id, :total_players)
end

def set_game
 @game = Game.find(params[:id])
end

_form parcel 用于新视图和编辑视图

<%= simple_form_for [@organiser, @game] do |f| %>
 <div class="form-inputs">
  <%= f.input :field_id, as: :select, collection: Field.all.collect(&:location) %>
  <%= f.input :total_players %>
 </div>

 <div class="form-actions">
  <%= f.button :submit, "Create", class: "btn btn-primary" %>
 </div>
<% end %>

我是初学者,如果你们能帮助我提供有助于我理解复杂部分的基本解决方案,我将不胜感激

我没有收到任何消息,它看起来像是通过了但实际上没有

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-5 associations simple-form-for


【解决方案1】:

collection: Field.all.collect(&amp;:location)

您的集合必须是一个包含关系 ID 和显示值的数组。在这里,您只为每个字段收集location 的值。

这段代码应该可以解决问题:

<%= f.input :field_id, as: :select, collection: Field.all.map { |field| [field.id, field.location] } %>

field.id 将是您选择选项的值(目前,没有值,因此无法使用),field.location 将是您选择选项的文本。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    相关资源
    最近更新 更多