Reputation: 21
I try to submit a form for a proposal. The form consists of choosing a model from a collection of countries and entering in a few text boxes. However, when I go to select the country, Rails says it is getting a string when it expects a country.
Proposal model:
class Proposal < ActiveRecord::Base
belongs_to :my_user, class_name: "User", foreign_key: "user_id"
belongs_to :country, class_name: "Country", foreign_key: "country_id"
after_initialize :set_defaults
validates :status, presence: true
validates :country, presence: true
validates :q1, length: {maximum: 250}
validates :q2, length: {maximum: 250}
.
.
.
validates :q30, length: {maximum: 250}
def set_defaults
self.status = "Pending"
end
end
Proposal controller:
class ProposalsController < ApplicationController
before_action :authenticate_user!, only: [:new, :create]
def index
@proposals = Proposal.all
end
def new
@proposal = Proposal.new
end
def create
@proposal = Proposal.new(params.require(:proposal).permit(:status, :country,
:q1,
:q2,
.
.
.
:q30))
@proposal.save!
redirect_to home_path
end
def display
@proposal = Proposal.find(params[:id])
end
end
View:
<div class="container-fluid text-center">
<div class="row content">
<div class="col-sm-12 text-left">
<%= form_for(@proposal) do |f| %>
<%= f.collection_select(:country, Country.all.order('name'), :id, :name) %>
<br><p><%= f.submit %></p><br>
<% end %>
</div>
</div>
</div>
Migration:
class CreateProposals < ActiveRecord::Migration
def change
create_table :proposals do |t|
t.string :status, :default => "Pending"
t.integer :country_id
t.text :q1
t.text :q2
.
.
.
t.text :q30
t.timestamps null: false
end
end
end
Upvotes: 0
Views: 1440
Reputation: 549
One think that I see is wrong in your example is that you permit :country instead of :country_id that you send from form. Let me know if that helped.
@proposal = Proposal.new(params.require(:proposal).permit(:status, :country_id, ...
Upvotes: 0
Reputation: 33542
You should change country
to country_id
in create
method
def create
@proposal = Proposal.new(params.require(:proposal).permit(:status, :country_id,
:q1,
:q2,
.
. .
:q30))
@proposal.save!
redirect_to home_path
end
Upvotes: 1