简体   繁体   中英

Rails has_many :through create association and associated model on parent “show” view

I have three models in my rails 5 application... What I want to do is to be able to create a note on the person's "show" view, then the note should automatically link to that person and any other person I choose to attach the note to.

Here's where I got up to

Note

class Note < ApplicationRecord
  has_many :person_notes
  has_many :people, through: :person_notes
  accepts_nested_attributes_for :person_notes
end

Person Note (Join table)

class PersonNote < ApplicationRecord
  belongs_to :person
  belongs_to :note
end

Person

class Person < ApplicationRecord
  has_many :person_notes
  has_many :notes, through: :person_notes
  accepts_nested_attributes_for :person_notes
  accepts_nested_attributes_for :notes
end

In my "show" section of my "people" controller I have the following:

def show
  @notep = Note.new()
  @person.notes << @notep
end

This is creating a join of a new note to my person record every time I open the page (obviously i only want the join to happen on the note I have created.)

I have rendered this in a modal as a partial in my "show" view (there is an "end" and a submit button but it's in between 3 divs and I know they weren't the cause of the issue so i didn't include them.:

<%= simple_form_for(@notep, remote: true) do |f| %>
<%= f.error_notification %>

  <%= f.input :subject %>
  <%= f.input :note %>
  <%= f.input :date, html5: true %>
  <div class="input-field">
     <%= f.check_box :isalert, :id => "alert" %>
     <%= f.label :isalert, :for => "alert" %>
  </div>

  <div class="input-field">
     <%= f.check_box :archived, :id => "archived" %>
     <%= f.label :archived, :for => "archived" %>
  </div>

  <div class="input-field">
     <%= f.check_box :deleted, :id => "deleted" %>
     <%= f.label :deleted, :for => "deleted" %>
  </div>
  <%= f.input :datecreated, html5: true %>
  <%= f.input :user_id %>


  <%= f.simple_fields_for :person_notes do |builder| %>
    <%= builder.association :person, label_method: :lstfstfullname %>
    <%= builder.input :deleted %>
    <%= builder.input :datecreated, html5: true %>
    <%= builder.input :user_id %>
  <% end %>

You can probably tell I'm a total newb, but I'd appreciate any help I can get.

Thanks,

Leah

If I'm understanding this correctly, you'll want a separate Notes controller and create action to handle note creation. Then in your People show view, you can add a form and input field that submits to NotesController#create.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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