AnthonyGalli.com
AnthonyGalli.com

Reputation: 2866

How to combine two date attributes in model method?

How can I create a method in the model to combine two date's so that I can iterate through it in next_user_challenge and previous_user_challenge

model

def challenge_date
  # deadline + date_started (some challenges have a deadline and others have date_started)
end

def next_user_challenge
  user.challenges.where('challenge_date > ?', challenge_date).order('challenge_date ASC').first
end

def previous_user_challenge
  user.challenges.where('challenge_date < ?', challenge_date).order('challenge_date ASC').last
end

view

<% if @challenge.previous_user_challenge %>
  <%= link_to 'Prev', challenge_path(@challenge.previous_user_challenge), class: "footer-left", style: "color: white; font-style: normal;" %>
<% else %>
  <%= link_to 'Home', root_url, class: "footer-left" %>
<% end %>

<% if @challenge.next_user_challenge %>
  <%= link_to 'Next', challenge_path(@challenge.next_user_challenge), class: "footer-right" %>
<% else %>
  <%= link_to 'Home', root_url, class: "footer-right" %>
<% end %>

rails c

# some challenges will just have a deadline
 id: 1,
 name: "Publish a Novel",
 deadline: Sat, 26 Nov 2016,
 date_started: nil,
 days_challenged: nil,
 category: "goal",
 user_id: 117,

# some challenges will just have a date_started
 id: 2,
 name: "Write a Chp",
 deadline: nil,
 date_started: Thu, 20 Oct 2016,
 days_challenged: 10,
 category: "habit",
 user_id: 117,

# and some challenges will have both
 id: 3,
 name: "Run a Mile",
 deadline: Thu, 26 Sep 2016,
 date_started: Thu, 26 Sep 2016, # If challenge has both deadline and date_started then date_started will be the same date as the deadline
 days_challenged: 30,
 category: "habit",
 user_id: 117,

Upvotes: 0

Views: 104

Answers (2)

Sivalingam
Sivalingam

Reputation: 931

create virtual attributes for those methods in model. So that column will be accessible in view.

attr_accessor :challenge_date
attr_accessor :next_user_challenge
attr_accessor :previous_user_challenge

Also you can use rails active_record scopes to achieve the same.

def challenge_date
   deadline || date_started  
end

Upvotes: 2

Waqas Awan
Waqas Awan

Reputation: 552

Hopefully this will help.

If both are not equal mean the case in which deadline or date_started is nil. Then it will return the one which is not nil. When both are present it return one of them as both are equal as mentioned in your use case.

def challenge_date
  if deadline != date_started
    [deadline, date_started].reject(&:blank?).join()
  else
    date_started
  end
end

Upvotes: 0

Related Questions