i can find a page I'm looking for just fine, like this:

  @my_page = ::Refinery::Page.find('foo')

so then i can say <% link_to @my_page.url %>

i then try and protect against the case where that page is deleted, like so:

  if ::Refinery::Page.find('foo').present?
    @my_page = ::Refinery::Page.find('foo')
  else
    @my_page = nil
  end

i've actually tries several ways of doing this, with exists?, with nil?, etc. the above is the most basic.

So I then go and delete my page and I get a record not found error.

Couldn't find Refinery::Page with id=foo

Shouldn't the present? method protect against that error? How should I be doing that?

有帮助吗?

解决方案

When you do

@my_page = ::Refinery::Page.find('foo')

it tries to find page by slug first and if it doesn't find it then it tries to find it by id. If you don't deal with localization you can do

@my_page = ::Refinery::Page.find_by_slug('foo')

which will return page if it finds it or nil if it doesn't.

With localization it get's complicated but this should do the trick

if ::Refinery::Page::Translation.find_by_slug('foo').present?
  @my_page = ::Refinery::Page::Translation.find_by_slug('foo').refinery_page
end

其他提示

How about following the principles of EAFP?

begin
  @my_page = Refinery::Page.find('foo')
rescue ActiveRecord::RecordNotFound
  @my_page = nil
end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top