【问题标题】:Undefined method 'permit' for "89718":String“89718”的未定义方法“允许”:字符串
【发布时间】:2017-03-04 20:17:38
【问题描述】:

我正在编写一个连接到旧版 SQL Server 数据库的简单 Rails api。我正在为我的联系人控制器测试我的 REST 操作。在使用 FactoryGirl 创建测试对象时,我遇到了标题中提到的错误消息。我的索引和显示操作工作正常,但创建操作抛出此错误。我的 contacts_controller 的相关部分如下所示:

def create
    contact = Contact.new(contact_params)
    if contact.save
        render json: contact, status: 201, location: [:api, contact]
    else
        render json: { errors: contact.errors }, status: 422
    end
end
...
private
    def contact_params
        params.require(:contact).permit(:name, :address_1, :city, :zip_code_5, :country)
    end

这里是相关的测试代码:

describe "POST #create" do
    context "when is successfully created" do
        before(:each) do
            @user = FactoryGirl.create :user
            @contact = FactoryGirl.create :contact
            post :create, { contact: @contact }
        end

        it "renders the json representation for the contact record just created" do
            contact_response = json_response
            expect(contact_response[:name]).to eq @contact_attributes[:name]
        end

        it { should respond_with 201 }
    end
end

型号:

class Contact < ActiveRecord::Base
    belongs_to :user

    validates :name, :address_1, :city, :zip_code_5, :country, :createddate, presence: true
end

序列化器(使用 active_model_serializer gem):

class ContactSerializer < ActiveModel::Serializer
    belongs_to :user
    attributes :id, :name, :address_1, :city, :zip_code_5, :country
end

我尝试过的事情包括:

  • 在序列化程序中将“belongs_to”更改为“has_one”(无更改)
  • 从 permite...require 行中删除“zip_code_5”(奇怪的是,我仍然收到有关此属性的错误消息,可能是因为序列化程序?)
  • 删除序列化程序(无变化)

有什么想法吗?我很乐意提供更多必要的信息。

编辑

@contact 传递给创建操作时的值:

#<Contact id: 89815, user_id: "d67b0d57-8f7f-4854-95b5-f07105741fa8", title: nil, firstname: nil, lastname: nil, name: "Alene Stark", company: nil, address_1: "72885 Bauch Island", address_2: nil, address_3: nil, city: "Joestad", state: nil, zip_code_5: "98117", zip_code_4: nil, country: "MF", status_id: 1, createddate: "2015-10-23 07:00:00", lastmodifieddate: "2012-11-29 08:00:00", errorreasonid: nil, computergenerated: true, sandbox: true, emailsubject: nil, jobtitle: nil, mergevar1: nil, mergevar2: nil, mergevar3: nil, mergevar4: nil, mergevar5: nil, mergevar6: nil, mergevar7: nil, mergevar8: nil, mergevar9: nil, mergevar10: nil, clientid: 1, isshared: true>

params[:contact] 在运行时的值:

{"city"=>"Seattle", "state"=>"WA", "zip_code_5"=>"98117", "country"=>"US"}

如果相关的话,我还将包装参数设置为 :json 格式。

【问题讨论】:

  • 出于某种原因,控制器中的params[:contact] 是一个字符串。你能检查你传递给post的@contact的值吗?也可以在运行时检查params[:contact] 的值并显示它是什么?

标签: ruby-on-rails ruby api serialization


【解决方案1】:

我使用控制台重新创建了我的测试正在执行的操作。我发现 Contact 是作为字符串而不是散列传递的。经过一番谷歌搜索后,我将@contact 对象作为@contact.attributes 传递,它传递了对象的哈希值。这解决了“许可”问题,感谢您指出正确的方向。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    相关资源
    最近更新 更多