Lesha Pipiev
Lesha Pipiev

Reputation: 3333

Rails Try Method

My models are Ticket, Staff, Post.

Ticket belongs_to Staff
Staff has_many Posts

I have The Ticket instance @ticket.
I would like to render all posts related with the ticket.
If there are no the related posts "No posts available" message will be shown.
My version is quite verbose:

if @ticket.staff and @ticket.staff.posts
  render @ticket.staff.posts
else 
  There are no answers available

But I would like to do it something more neatly.

= render(@ticket.staff.try(:post).any?) || "There are no answers available"

It gives me an error 'nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.

Any ideas?

Upvotes: 0

Views: 141

Answers (1)

sonnyhe2002
sonnyhe2002

Reputation: 2121

In your ticket model you can 'delegate'

delegate :posts, to: :staff, allow_nil: true

In the controller make an instance variable.

@posts = ticket.posts

And in your view

-if @post.present?
  =render @posts
-else
  There are no answers available

Upvotes: 1

Related Questions