Ruby/Rails/Rspec - ActiveRecord::AssociationTypeMismatch: [英] Ruby/Rails/Rspec - ActiveRecord::AssociationTypeMismatch:

查看:32
本文介绍了Ruby/Rails/Rspec - ActiveRecord::AssociationTypeMismatch:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这是我的 rspec 代码...

OK, here's my rspec code ...

        before(:each) do
            @attr = { :greeting => "Lorem ipsum", :recipient => @recipient }
        end

        it "should redirect to the home page" do
            puts "spec: @attr = #{@attr}"
            puts "spec: recipient = #{@attr[:recipient]}"
            post :create, :card => @attr
            response.should redirect_to(root_path)
        end

现在的输出是:

spec: @attr = {:greeting=>"Lorem ipsum", :recipient=>#<User id: 2, first_name: "Example", last_name: "User", email: "recipient@example.com", created_at: "2011-12-22 04:01:02", updated_at: "2011-12-22 04:01:02", encrypted_password: "2d1323ad5eb21fb5ae5e87dfa78a63b521c56833189cc049ee2...", salt: "2679fcc29a30e939541cb98cb65d1d508035fea0eff1136037a...", admin: false>}
spec: recipient = #<User:0xac5d80c>

所以我们可以看到收件人是一个用户.

So we can see that recipient is a User.

在控制器端,我们看到有...

On the controller side, we see have ...

def create
    puts "create: Params = #{params}"
    @card = current_user.sent_cards.build(params[:card])
    if @card.save
        flash[:success] = "Card created!"
        redirect_to root_path
    else
        render 'pages/home'
    end
end

显示...

create: Params = {"card"=>{"greeting"=>"Lorem ipsum", "recipient"=>"2"}, "controller"=>"cards", "action"=>"create"}

我看到一个错误...

1) CardsController POST 'create' success should create a card
   Failure/Error: post :create, :card => @attr
   ActiveRecord::AssociationTypeMismatch:
     User(#90303150) expected, got String(#76171330)
   # ./app/controllers/cards_controller.rb:7:in `create'
   # ./spec/controllers/cards_controller_spec.rb:47:in `block (5 levels) in <top (required)>'
   # ./spec/controllers/cards_controller_spec.rb:44:in `block (4 levels) in <top (required)>'

那么…… User 对象是如何变成字符串的 id 的?有什么想法吗?

So ... how did the User object get changed into its id as a string? Any ideas?

推荐答案

您不能将整个对象作为参数传递.如果它有一个对象,Rails 会用它的 id 替换对象,否则传递对象的字符串表示,即 # 如果它没有找到 id.

You cannot pass an entire object as a parameter. Rails replaces the object with its id if it has one or else passes a string representation of the object i.e. #<User:0xac5d80c> for your case if it doesn't find the id.

因此,对于您的情况,您应该将 :recipient 参数重命名为 :recipient_id.然后

So for your case, you should rename the :recipient parameter to :recipient_id. Then

@card = current_user.sent_cards.build(params[:card]) 

将创建您的卡与关联的收件人,因为我们已经传入了 receiver_id.

will create your card with the associated recipient as we have passed in the recipient_id.

这篇关于Ruby/Rails/Rspec - ActiveRecord::AssociationTypeMismatch:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆