2016-05-06 6 views
0

ユーザがsubmitをクリックすると、2つの異なるモデル/ DBテーブルの情報はどのように受け継がれますか?2つのモデル(3番目のモデルに属する)を1つのサブミットで保存しますか?

missed_datesフォームにnoteを作成することができます。そのメモは、逃した日付を指している@challengeに保存する必要があります。

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 %> 

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

missed_date_controller missed_date.rb

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 

答えて

1

Short:ノートとMissedDateの間に "belongs_to"と "has_many:through"の関連付けを使用します。次に、ネストされた属性を使用できます。

ロングバージョン:モデルの不適切な構造や不完全な構造の問題が考えられます。通常、ネストされた属性(http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.htmlを参照)を使用してこれを実現できます。

しかし、これはモデルが直接の関係を持っていることを意味します。 noteとmissed_dateモデルの間にbelongs_to/has_manyリレーションを実行できるかどうかを検討する必要があります。これは、例えば、 "has_many:through ..."(http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association)によって、現在のdbスキームを変更する必要はありません。

+0

私はフォームの中で正しいと言いましたか?私はそれを試みたが、私はまだエラーが発生します。私は 'submit'が知らないので、どのフォームを提出するべきなのかもしれないと思いますか? –

+0

http://stackoverflow.com/questions/2182428/rails-nested-form-with-has-many-through-how-to-edit-attributes-of-join-model-こちらをご覧ください。結合されたテーブル全体でネストされたモデルとフォームを使用します。 「has_many:through」を使用しましたが、「accepts_nested_attributes_for」を追加しましたか?結合モデルとターゲットモデルで「ビルド」を呼び出しましたか?あなたがこのすべてをやったのなら、pls。あなたが実際に何をしたのかを書き留めておきましょう。明日の実例を立てようとします(今は0時30分です。 –

関連する問題