【问题标题】:Creating default values in a new form derived from an associated model instance以从关联模型实例派生的新形式创建默认值
【发布时间】:2013-06-11 01:09:30
【问题描述】:

我想在创建新记录时使用 simple_form 使用存储在关联模型中的数据填充表单字段。

class Game < ActiveRecord:Base
  has_many :events
  attr_accessible :name, :number_of_players
end

class Event < ActiveRecord:Base
  belongs_to :game
  attr_accessible :name, :number_of_players
end

不同的比赛需要不同数量的队员加入(棒球:9,篮球:5,足球:11)。

在我的表单中,创建事件时,我有一个关联下拉列表,用户可以在其中选择游戏。我想为玩家数量预先填充一个事件字段,如果需要,用户可以覆盖它。例如,篮球将使用 5 填充该字段,但用户可能希望将其更改为 3,因为该特定事件可能是 3 对 3 游戏。我不想修改游戏数据。

本质上,我正在尝试根据在同一表单中选择的关联模型实例的值为表单创建默认值。我尝试了很多方法都没有成功。

【问题讨论】:

    标签: ruby-on-rails-3.2 simple-form model-associations


    【解决方案1】:

    怎么样:

    <%= f.input :number_of_players, :input_html => { :value => (number_of_players_value(f.object)} %>
    

    定义一个number_of_players_value 辅助方法:

    def number_of_players_value(event)
      event.new_record? ? event.game.number_of_players : event.number_of_players
    end
    

    此解决方案默认情况下,事件具有关联的游戏。 如果在用户选择其他游戏时应该更改 number_of_players 字段的内容,那么您需要一些 JavaScript 来实现这一点。

    【讨论】:

    • 我忘了回复您的回答,这确实为我正在寻找的行为提供了一种新方法。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多