我正在使用偏执 gem 。
我的数据库中有一堆项目,但出于某种原因,它们的行为就像被删除了一样。当我导航到我的 projects/1 路线时,出现错误:
Couldn't find Project with id=1 [WHERE "projects"."deleted_at" IS NULL]
当我在控制台中输入时:
Project.find(1).deleted_at
我明白了
nil
这里发生了什么?
这是我的 Controller 显示 Action :
def show
@project = Project.find(params[:id])
@comments = Comment.all.where(:project_id => @project.id)
@updates = ProjectUpdate.all.where(:project_id => @project.id)
end
错误发生在
@project = Project.find(params[:id])
以下是一些模型项目范围:
scope :by_category, lambda {|category| {:conditions => {:category_id => category.id}}}
scope :by_npo, lambda {|npo| {:conditions => {:npo_id => npo.id}}}
使用 Project.find(1)
我得到:
=> #<Project id: 1, name: "project 1", npo_id: 1, description: "project1 description", location_id:
4, singular_unit: "1", past_tense_action: "past tense action", conversion: #<BigDecimal:7547d78,'0.1
5E1',18(45)>, created_at: "2014-05-13 00:12:33", updated_at: "2014-05-22 01:20:51", future_tense_act
ion: "future tense action", plural_unit: "2", amount1: #<BigDecimal:75475b0,'0.1E2',9(36)>, amount2:
#<BigDecimal:7547520,'0.2E2',9(36)>, amount3: #<BigDecimal:7547490,'0.3E2',9(36)>, min_amount: nil,
other_amount: true, short_description: "project1 short description", featured_image_id: 3, deleted_
at: nil>
从我的索引页面我链接到它 2ice(这是相关代码:
<div class="pj">
<h5><%= link_to project.name, project, :class => "button-link" %> </h5>
<hr />
<div class="index_featured_image">
<%= link_to image_tag(project.get_featured_image, :alt => "Project Title", class: "featured_image"), project %>
</div>
<div class="proj-content">
<p><strong><%= link_to project.npo.name, npo_path(project.npo) %></strong></br>
<%= project.short_description %></p>
</div>
<div>
<p class="project-loc"><i class="footicons fi-marker large"></i> <%= project.location.city_state %></p>
</div>
<div class="text-center">
<%= button_tag :type => "button", :class => "radius" do %>
<%= link_to "View More", project, :class => "button-link" %>
<% end %>
</div>
</div>
最佳答案
一些猜测和一些建议。
先说猜测。如果 Project.find(params[:id])
在表上调用 WHERE "projects"."deleted_at"IS NULL
条件,则必须有一个 default_scope
调用项目。虽然仍然很奇怪为什么 id 会阻止 find 方法找到正确的项目,如果它真的没有被删除的话。让我看看 default_scope(或者最好只是将整个模型发布到要点中),我可能会说得更多。
现在一些建议。它与当前问题并没有真正的关系,但我相信,它会让你现在的 Rails 生活变得更加轻松。
尽量不要使用过时的语法,继续使用新语法。 例如。这些作用域调用应该是这样的
scope :by_category, ->(category){where(category_id: category.id)}
不要将
.all
与.where
一起使用。你只是不需要它。.where
调用将返回您要查找的 ActiveRecord::Relation 对象。尽量减少 Controller 中实例变量的数量。例如,您可以在
show
操作中省略@comments
和@updates
变量的使用,前提是您已经设置了所需的关联项目模型。has_many :comments has_many :updates, class_name: ProjectUpdate
然后在 View 中您可以将它们称为@project.comments 和@project.updates 而无需单独存储它们。它会稍微清理一下 Controller 。另外,如果你想确保评论和更新不是延迟加载的,你可以通过调用
@project = Project.includes(:comments, :updates).find(params[: id])
.
希望对您有所帮助。如果我对问题有更具体的说明,我会更新答案。
关于sql - 找不到 id=1 的项目 [WHERE "projects"."deleted_at"IS NULL],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24104834/