【问题标题】:ruby on rails TypeError in Users#show - Cannot visit Likeruby on rails TypeError in Users#show - 无法访问喜欢
【发布时间】:2012-09-08 18:42:09
【问题描述】:

导致问题的形式:

<%= form_for Like.find(post.user.likes), :html => { :method => :delete , :class => "unlike_post_like_form" } do |f| %>

后模型

belongs_to :user
has_many :likes

用户模型

  has_many :posts
  has_many :likes

喜欢模特

  belongs_to :post
  belongs_to :user

我不断收到以下错误:

TypeError in Users#show 
Cannot visit Like

Like.find(post.user.likes),

编辑:

第一个解决方案:

变化

Like.find(post.user.likes),

Like.find(post.user.likes).limit(1),

第二种解决方案:

变化

Like.find(post.user.likes),

current_user.likes.where(:post_id => post.post_id)

【问题讨论】:

    标签: ruby-on-rails model associations typeerror


    【解决方案1】:

    Like.find(post.user.likes) 正在尝试在给定likes 数组的情况下查找Like。这真的没有多大意义。

    您很可能会想要搜索 post.user.likes,但即便如此,我还是有点困惑 - 您需要发布更多代码。

    Like.find 正在寻找 id(整数)或包含键和值的散列。数组不给它任何搜索信息。

    编辑:如果您正在寻找当前用户的喜欢。您需要执行以下操作...

    current_user.likes.where(:post =&gt; @post)

    【讨论】:

    • @fxuser 谁的like.id?正如您所定义的,一个帖子有很多赞。也许current_user
    • 我的意思是 current_user... 又名我的
    • @fxuser 使用以下内容编辑了我的原始评论:current_user.likes.where(:post =&gt; @post)
    【解决方案2】:

    类型错误来自于将集合(post.user.likes - 这是一个数组)传递给需要记录 id 的方法,例如 Likes.find(3)Likes.find(params[:id])

    【讨论】:

    • 我们也可以“找到”资源集合:&gt; User.find([2, 3])=&gt; [#&lt;User id: 2, ...&gt;, #&lt;User id: 3, ...&gt;]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    相关资源
    最近更新 更多