简体   繁体   English

用一个提交保存两个模型(属于第三个模型)?

[英]Save two models (which belong_to a third model) with one submit?

When the user clicks submit how can the info from two different models/DB tables be passed? 当用户单击submit如何传递来自两个不同模型/数据库表的信息?

The user should be able to create a note in the missed_dates form and then that note should be saved to the respective @challenge the missed date is referring to. 用户应该能够在missed_dates表单中创建一个note ,然后将该便笺保存到错过的日期所指的相应@challenge中。

missed_dates/form.html.erb missed_dates / form.html.erb

<%= simple_form_for(@missed_date, url: challenge_missed_dates_path({ routine_id: @challenge }), remote: request.xhr?, html: { data: { modal: true } }) do |a| %>
<%= form_for [@notable, @note] do |b| %>
  <%= a.text_field :one %>
  <%= b.text_field :two %>
  <%= button_tag(type: 'submit')  do %>
    Save
  <% end %>
<% end %>
<% end %>

missed_date.rb missed_date.rb

class MissedDate < ActiveRecord::Base
  belongs_to :user
  belongs_to :challenge
end

missed_date_controller missed_date_controller

  def new
    @challenge = current_user.challenges.find(params[:challenge_id])
    @missed_date = current_user.missed_dates.build
    @notable = @challenge
    @note = Note.new
  end

  def create
    challenge = current_user.challenges.find(params[:challenge_id])
    challenge.missed_days = challenge.missed_days + 1
    challenge.save
    @missed_date = challenge.missed_dates.build(missed_date_params)
    @missed_date.user = self.current_user
    @missed_date.save
    respond_modal_with @missed_date, location: root_path
    flash[:alert] = 'Strike added'
  end

Short: use "belongs_to" and "has_many :through" association between Note and MissedDates. 简短:在Note和MissedDates之间使用“ belongs_to”和“ has_many:through”关联。 Then you can use nested attributes. 然后,您可以使用嵌套属性。

Long version: This in probably an issue of an improper or incomplete structure of your models. 长版:这可能是模型结构不正确或不完整的问题。 Usually, you can use nested attributes (see http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html ) to achieve this. 通常,您可以使用嵌套属性(请参见http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html )来实现此目的。

But, this implies that the models have a direct relation. 但是,这意味着模型具有直接关系。 You should consider if you can do a belongs_to/has_many relation between the note and the missed_date model. 您应该考虑是否可以在便笺和missed_date模型之间建立belongs_to / has_many关系。 This could be done eg by "has_many :through..." ( http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association ) without changing your current db scheme. 这可以通过“ has_many:through ...”( http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association )完成,而无需更改当前的数据库方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM