我该如何使用||运算符如此破坏发生在2个实例中的哪一个?

时间:2014-11-24 01:23:33

标签: ruby-on-rails variables parameters operators destroy

我有两种情况需要破坏关系。 1.删​​除活动关系时 2.删除被动关系时。

目前每种情况都适用于它自己。但是当我尝试设置它以便同时工作时我得到一个有效的记录错误。 它与destroy方法有关,无法在两次出现中找到params [:id]的关系。也许是我如何使用||操作

目前,如果我尝试删除被动关系,它会起作用。但是如果我尝试删除一个活动的,我会得到如下所示的活动记录错误:

ActiveRecord::RecordNotFound in RelationshipsController#destroy
Couldn't find Relationship with 'id'=1 [WHERE "relationships"."followed_id" = ?]

如果我更改了代码,那么def destroy在被动之前就已激活:

@relationship = current_user.active_relationships.find(params[:id]) || current_user.passive_relationships.find(params[:id]) 

然后active_relationship delete工作,但passive_relationship delete返回活动记录问题。 (这次是:

ActiveRecord::RecordNotFound in RelationshipsController#destroy
    Couldn't find Relationship with 'id'=1 [WHERE "relationships"."follower_id" = ?]

如果

,我该如何让它知道呢?
@relationship = current_user.active_relationships.find(params[:id]) || current_user.passive_relationships.find(params[:id]

只使用提供的ID找到其中一个关系?

人际关系/编辑:(查看)

<% if @active_relationship %>
    <% if @active_relationship.pending? %>
        <%= form_for @active_relationship, url: relationship_path(@active_relationship), method: :delete do |form| %>
        <%= submit_tag "Delete Request", class: 'btn btn-danger' %>
        <% end %>
    <% end %>
<% end %>

<% if @passive_relationship %>
    <% if @passive_relationship.pending? %>
        <%= form_for @passive_relationship, url: relationship_path(@passive_relationship), method: :delete do |form| %>
        <%= submit_tag "Decline Relationship", class: 'btn btn-danger' %>
        <% end %>
    <% end %>
<% end %>

关系控制器:

def destroy
    @relationship = current_user.passive_relationships.find(params[:id]) || current_user.active_relationships.find(params[:id])
    if @relationship.destroy
      flash[:success] = "Relationship destroyed"
    end
    redirect_to root_path
  end

1 个答案:

答案 0 :(得分:1)

试试这种方式。

在app / models / user.rb(User)中创建方法:

def find_by_passive_or_active_relatioship(id)
  passive_relationships.where(id: id).first || active_relationships.where(id: id).first
end

然后在你的控制器中:

def destroy
  @relationship = current_user.find_by_passive_or_active_relatioship(params[:id])
  if @relationship.try(:destroy)
    flash[:success] = "Relationship destroyed"
  else
    flash[:error] = 'Relationship can be destroyed at the moment. Try again.'
  end
  redirect_to root_path
end

您可以使用find_by方法代替where(id: id),具体取决于您的Rails版本。

find如果找不到资源,则会引发RecordNotFound异常,而where().firstfind_by方法则不会。