Santosh Mohanty
Santosh Mohanty

Reputation: 482

Rails dummy object added to Active Record Array

I use rails 4.2 and I found a weird issue:

 @tweet = current_user.tweets.new
 @tweets = current_user.tweets

When I loop over in Views like:

<%= render @tweets %>

I get an Extra Record with null id.

Example:

Error Image

Upvotes: 1

Views: 855

Answers (1)

spickermann
spickermann

Reputation: 106802

You build this empty Tweet yourself in your controller:

@tweet = current_user.tweets.new
@tweets = current_user.tweets

There are several ways to avoid this problem. You could build the new Tweet without adding it to the @tweets array:

@tweet = Tweet.new(user: current_user)
@tweets = current_user.tweets

Or you could change your your to exclude tweets that haven't been saved to the database yet:

<%= render @tweets.select(&:persistent?) %>

Upvotes: 3

Related Questions