【问题标题】:undefined method `find_by'未定义的方法“find_by”
【发布时间】:2014-10-24 07:07:45
【问题描述】:

我是 ruby​​ on rails 的新手,所以请帮助我 :) 这是我的错误

NoMethodError in Welcome#sucess   
Showing ..app/views/welcome/sucess.html.erb where line #8 raised:    
undefined method `find_by' for #<ActiveRecord::Relation:0x41dca80>
Extracted source (around line #8):

5: <%= @user.pass%><br />
6: <% if current_user && current_user != @user %>
7:   <% if current_user.following.include?(@user) %>
8:     <%= form_for(current_user.following_relations.find_by(following_id: @user.id),
9:              html: { method: :delete }) do |f| %>
10:   <%= f.submit "Unfollow", class: "btn" %>
11: <% end %>

这是我的关系控制器

def destroy
    user = Relations.find(params[:id]).following
    current_user.unfollow(user)
    redirect_to user
  end

我的用户模型

  def unfollow(other_user)
    following_relations.find_by(following_id: other_user.id).destroy
  end

请帮我解决这个问题

【问题讨论】:

  • 您使用的是哪个版本的 Rails? find_by 仅适用于 >= 4.0 的 rails
  • 我使用的是 rails 版本 3.2.19

标签: ruby-on-rails ruby


【解决方案1】:

由于您使用的是不支持 find_by() 的 Rails (3.2.19) 版本,因此您需要使用旧的 dynamic finders。

所以如果你改变它很可能会起作用:

def unfollow(other_user)
  following_relations.find_by(following_id: other_user.id).destroy
end

到

def unfollow(other_user)
  following_relations.find_by_following(other_user.id).destroy
end

【讨论】:

    【解决方案2】:

    你可以试试这个:

    <%= form_for(current_user.following_relations.find_by_following_id(@user.id),html: { method: :delete }) do |f| %>
    

    型号:

    def unfollow(other_user)
        following_relations.find_by_following_id(other_user.id).destroy
      end
    

    希望有效果

    【讨论】:

    • 解释为什么这会很好,因为这是公认的答案。
    • @sevenseacat 好吧,Rails find_by 正在寻找最具体的条件。因此,如果您在 find_by 上指定属性条件,它可以工作,您还可以指定 8:&lt;%= form_for(current_user.following_relations.find_by(:following_id =&gt; @user.id)
    • 这完全不是您的答案正确的原因。请参阅下面罗宾的回答。
    • @sevenseacat 对不起,我接受罗宾的解释对我的回答是正确的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 2013-06-11
    • 2010-12-30
    相关资源
    最近更新 更多