未定义的方法'许可' for" 89718":String

时间:2016-10-22 17:22:25

标签: ruby-on-rails ruby api serializer

我正在编写一个连接到旧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

我尝试过的事情包括:

  • 更改&#39; belongs_to&#39;到了&#39; has_one&#39;在序列化器中(无变化)
  • 删除&#39; zip_code_5&#39;来自permite ...需要行(奇怪的是,我仍然收到有关此属性的错误消息,可能是因为序列化程序?)
  • 删除序列化程序(无更改)

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

修改

@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格式,如果相关的话。

1 个答案:

答案 0 :(得分:2)

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