加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 嵌套模型表单中的Collection_select

发布时间:2020-12-16 21:37:55 所属栏目:百科 来源:网络整理
导读:我有时间表模型,运行模型和运动员模型. class Timesheet ActiveRecord::Base has_many :runs,:dependent = :destroy accepts_nested_attributes_for :runsendclass Run ActiveRecord::Base belongs_to :timesheet belongs_to :athleteendclass Athlete Activ
我有时间表模型,运行模型和运动员模型.
class Timesheet < ActiveRecord::Base
  has_many :runs,:dependent => :destroy
  accepts_nested_attributes_for :runs
end


class Run < ActiveRecord::Base
  belongs_to :timesheet
  belongs_to :athlete
end

class Athlete < ActiveRecord::Base
  has_many :runs
end

运行嵌套在Timesheets下,我想在创建Timesheet的同一表单上创建一些运行,如此railscast所示

class TimesheetsController < ApplicationController
  def new
    @timesheet = Timesheet.new
    3.times { @timesheet.runs.build }
  end

在我的时间表表单上,我遇到了我的collection_select问题(运动员名称的下拉列表填充了运行表中的:athlete_id字段).

<% form_for(@timesheet) do |f| %>
  <%= f.error_messages %>
  <%= f.label "Date" %>
  <%= f.text_field :date %>

  <% f.fields_for :runs do |builder| %>
    <%= collection_select(:run,:athlete_id,Athlete.all(:order => 'name'),:id,:name,{ :prompt => 'Select Athlete' } ) %>
  <% end %>

<%= f.submit 'Create' %>

<% end %>

是否可以使用如上所示的collection_select填充Run的:athlete_id字段,在Timesheet的嵌套表单中,或者我错过了什么?

解决方法

看起来你没有在表单构建器上创建集合选择,尝试这样的事情:
<% f.fields_for :runs do |r| %>
  <%= r.collection_select(:athlete_id,{ :prompt => 'Select Athlete' } ) %>
<% end %>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读