如何通过我的Rails表单创建/删除关联对象?

时间:2016-03-01 14:40:22

标签: ruby-on-rails twitter-bootstrap associations simple-form multi-select

我想要从我的主表单对象Report添加/删除记录到关联。我正确显示了多选下拉列表,并正确地将ID传递给我的更新操作。但是,我收到以下消息。

Couldn't find all ReportExposures with 'id': (157504, 148644, 152852) (found 0 results, but was looking for 3)

现在我知道那些ID实际上是我想要分配给ncaa_game_id记录的ReportExposure,但是我不能将ReportExposure id放在class Report < ActiveRecord::Base has_many :report_exposures end 因为它没有真的存在了。我需要在表单上调整什么才能使其正常工作,或者我需要在更新操作中添加一些代码来处理这些代码?

Report.rb

class ReportExposure < ActiveRecord::Base
  belongs_to :ncaa_game
  belongs_to :report
end

ReportExposure.rb

def update

  # "report_exposure_ids"=>["157504","148644","152852"] -- these ids are really the ncaa_game_ids I want to create new report_exposure objects with...

  respond_to do |format|
    if @report.update(report_params)
      format.html
      format.json
    end
  end

end

ReportsController.rb

<select id="report_report_exposure_ids" name="report[report_exposure_ids][]" class="multiselect-dropdownlist" multiple="multiple">
  <% @exposures.each do |season| %>
    <optgroup label="<%= season.first.season %> Season">
      <% season.includes(:home_team, :away_team).order(game_date: :asc).each do |game| %>
        <option value="<%= game.id %>"><%= game.full_description %></option>
      <% end %>
    </optgroup>
  <% end %>
</select>

_form.html.erb

# create a dummy DataFrame
df = pd.DataFrame( np.random.randint(2, size=(6,4)), columns=['col_1', 'col_2', 'col_3', 'col_4'],  index=range(6)  )

# create a dict with your desired substitutions:
swap_dict = {  0 : 'a',
               1 : 'b',
             999 : 'zzz',  }

# introduce new column and fill with swapped information:
for i in df.index:
    df.loc[i, 'new_col'] = swap_dict[  df.loc[i, 'col_1']  ]

print df

1 个答案:

答案 0 :(得分:1)

将报告更改为:

class Report < ActiveRecord::Base
  has_many :report_exposures
  has_many :ncaa_games
  accepts_nested_attributes_for :ncaa_games
end

阅读有关在此处执行嵌套表单的信息:

http://guides.rubyonrails.org/form_helpers.html#nested-forms

有很多人通过has_many关系询问有关nested_forms的问题。看一下这些指导:

Rails has_many :through nested form

除非您实际处理向该对象添加元数据,否则不要尝试操纵连接对象(ReportExposure)。这就是ORM的用途。