Controller中的ActiveRecord :: AssociationTypeMismatch(rails)

时间:2016-04-06 08:09:16

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord

我尝试提交提案表单。表单包括从一组国家/地区中选择一个模型并输入几个文本框。但是,当我选择国家时,Rails表示在预期某个国家时会收到一个字符串。

提案模型:

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

提案管理员:

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

查看:

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

迁移:

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

2 个答案:

答案 0 :(得分:0)

您应该在country方法

中将country_id更改为create
def create
  @proposal = Proposal.new(params.require(:proposal).permit(:status, :country_id,
  :q1, 
  :q2,
  .
  .        .
  :q30))
  @proposal.save!
  redirect_to home_path
end

答案 1 :(得分:0)

有人认为我看到你的例子中的错误是你允许:country而不是:你从表单发送的country_id。如果有帮助,请告诉我。

@proposal = Proposal.new(params.require(:proposal).permit(:status, :country_id, ...