Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To do this the MVC way, I would probably push this logic on the thing that 'owns' the statements. After all a statement usually belongs to something. After reading the comments though, it sounds like this is an inherited project. If not you have to ask why would you have a 'months' relationship, when the statement has a <code>created_at</code> column you can tie into? Here is what i came up with, it may not be helpful to you. Although do checkout <code>Date::MONTHNAMES</code> at the very least it sounds like that might be helpful to you.</p> <pre><code>describe User do before(:each) do @user = User.create! end it "should know about months" do Statement.create(:user =&gt; @user) @user.statements.last.month_name.should == "November" end it "should report last months statement as nil when there is no statement" do @user.last_months_statement.should be_nil end it "should report last months statement as nil if there is only one for this month" do Statement.create(:user =&gt; @user) @user.last_months_statement.should be_nil end it "should report a statement from the previous month if there is one" do target = Statement.create(:user =&gt; @user, :created_at =&gt; 1.month.ago) Statement.create(:user =&gt; @user) @user.last_months_statement.should == target end it "should report last months statement if there a several" do Statement.create(:user =&gt; @user, :created_at =&gt; 1.month.ago) Statement.create(:user =&gt; @user) Statement.create(:user =&gt; @user, :created_at =&gt; 2.months.ago) @user.last_months_statement.month_name.should == "October" end end class User &lt; ActiveRecord::Base has_many :statements, :order =&gt; "created_at" def last_months_statement if statements.size &lt;= 1 || statements.last.created_at.month &lt; Time.now.month nil else index = statements.index(statements.last) statements[index - 1] end end end class Statement &lt; ActiveRecord::Base belongs_to :user def month created_at.month end def month_name Date::MONTHNAMES[created_at.month] end end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload