用户上的ruby on rails TypeError#show - 无法访问Like

时间:2012-09-08 18:42:10

标签: ruby-on-rails model associations typeerror

导致问题的

表单:

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

on

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)

2 个答案:

答案 0 :(得分:5)

Like.find(post.user.likes)正在尝试找到Like给定一个likes数组。这并没有多大意义。

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

Like.find正在查找id(整数)或包含键和值的哈希。数组没有给它任何搜索信息。

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

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

答案 1 :(得分:1)

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