简体   繁体   中英

Can't save data from collection_select helper to model

I'm trying to save an organization to a contact model via a form using a collection_select helper but it's not saving the data to a model. I can't seem to understand why.

I am using Rails 5.1.4

Here are my contact.rb model:

class Contact < ApplicationRecord
belongs_to :organization
has_many :deals
end

Here is my organization.rb model:

class Organization < ApplicationRecord
has_many :deals, through: :contacts
has_many :contacts, dependent: :destroy
end

Here is my schema.rb :

create_table "contacts", force: :cascade do |t|
t.string "contact_name"
t.integer "organization_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["organization_id"], name: 
"index_contacts_on_organization_id"
end

create_table "organizations", force: :cascade do |t|
t.string "org_name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end

Here is my contacts_controller.rb :

def new
@contact = Contact.new
end

def edit
@contact = Contact.find(params[:id])
end

def create
@contact = Contact.new(contact_params)

if @contact.save
redirect_to @contact
else
render 'new'
end
end

private

def contact_params
params.require(:contact).permit(:contact_name, :organization_id,
                                organizations_attributes: [:org_name, 
:id])
end 

Here is my new.html.erb file:

<h1>New Contact</h1>

<%= form_with scope: :contact, url: contacts_path, local: true do |form| %>

<p>
<%= form.label :contact_name %><br>
<%= form.text_field :contact_name %>
</p>

<p>
<%= form.label :organization %><br>
<%= form.collection_select(:organization_id, Organization.all, :id, :org_name) %>
</p>

<p>
<%= form.submit %>
</p>
<% end %>
<hr>

Edit: I added params for my controller and schema.

In organization.rb model:

class Organization < ApplicationRecord
  has_many :deals, through: :contacts
  has_many :contacts, dependent: :destroy

  def org_name
    "#{name}"
  end
end

in your new.html.erb file:

<%= form.fields_for :organizations do |o| %>
  <%= o.collection_select(:organization_id, Organization.all,
                          :id, :org_name,
                          {:prompt => 'Please select the organization'}) %>

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