João Daniel
João Daniel

Reputation: 8976

Get unsaved associations from inside the model

How can I access unsaved associations from inside a model method? For example:

class Post < ActiveRecord::Base
  has_many :comments

  def comment_dates
    comments.pluck(:created_at).sort
  end
end

The comments method called inside a model method returns just already saved associations. When I call the method from the object, e.g. post.comments it returns both saved and unsaved associations.

How can I access saved and unsaved associations from inside a model method? I need this to do some complex validation including associations.

Upvotes: 4

Views: 1620

Answers (1)

Paweł Dawczak
Paweł Dawczak

Reputation: 9639

How about something like this?

class Post < ActiveRecord::Base
  has_many :comments

  def comment_dates
    comments.pluck(:created_at).sort
  end

  def comments_dates_no_query
    comments.map(&:created_at).sort
  end

  def unsaved_comments
    comments.reject(&:persisted?)
  end

  def saved_comments
    comments.select(&:persisted?)
  end
end

You can us it like

post.saved_comments

or

post.unsaved_comments

Hope that helps!

Upvotes: 1

Related Questions