0

When the user clicks submit how can the info from two different models/DB tables be passed?

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

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

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
AnthonyGalli.com
  • 2,796
  • 5
  • 31
  • 80

1 Answers1

1

Short: use "belongs_to" and "has_many :through" association between Note and MissedDates. 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.

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. This could be done e.g. by "has_many :through..." (http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association) without changing your current db scheme.

  • So you saying I got it right in the form? I tried that but I still get error. I think it might be because `submit` doesn't know, which form to submit for? – AnthonyGalli.com May 07 '16 at 17:18
  • Please take a look at http://stackoverflow.com/questions/2182428/rails-nested-form-with-has-many-through-how-to-edit-attributes-of-join-model - it explains how to use nested models and forms throughout joined tables. Have you used "has_many :through", did you add "accepts_nested_attributes_for"? Did you call 'build' on your join model and on the target model? If you did all this pls. give me a note about what you actually did and I will try to set up a working example tomorrow (it's 0:30am here right now, so gonna take some sleep...) – Markus Buschhoff May 07 '16 at 22:38