t56k
t56k

Reputation: 6981

Rails: if record exists then use this record

How do I use the result of an if condition in Rails? Something like:

if @edits.where(:article_id => a.id).first
  THIS.body.html_safe
else
  a.body.html_safe
end

How on earth do I access the result of that condition? That being the THIS record?

Thanks!

Upvotes: 2

Views: 179

Answers (4)

Dennis
Dennis

Reputation: 59509

You can use find_by or find_by_* to avoid the nasty .where().first

if edit = Edit.find_by(article_id: article.id)
  edit.body.html_safe
else
  article.body.html_safe
end

Upvotes: 0

Billy Chan
Billy Chan

Reputation: 24815

Putting such logic in view or helper is very ugly. It's not View's job to judge these.

Better alternative:

# Article model
def default_edit
  edits.first
end

# Articles Controller
def show
  article = Article.find(params[:article])
  @article = article.default_edit || article
end

# view: no need to do anything, just plain obj
<%= @article.body %>

Upvotes: 1

xdazz
xdazz

Reputation: 160843

You could write in one line:

(@edits.where(:article_id => a.id).first || a).body.html_safe

Upvotes: 1

ipd
ipd

Reputation: 5714

You can do the assignment within the if statement.

if edit = @edits.where(:article_id => a.id).first
  edit.body.html_safe
else
  a.body.html_safe
end

Upvotes: 2

Related Questions