I am trying to display and capture only the “most recent” item from a *has_many* relationship. Basically, I want to find a single object that exists in a *has_many* relationship (based on some criteria) and display that with the record.
I have the class relationships defined like so (stripped down):
class Member < ActiveRecord::Base
has_many :member_status_histories
has_many :member_statuses, :through => :member_status_history
end
class MemberStatusHistory < ActiveRecord::Base
belongs_to :member_status
belongs_to :member
has_one :timespan
end
class MemberStatus < ActiveRecord::Base
attr_accessible :name
has_many :memberStatusHistories
has_many :members, :through => :memberStatusHistories
end
class Timespan < ActiveRecord::Base
attr_accessible :startDate, :endDate
belongs_to :timespanable, :polymorphic => true
end
Specifically using the classes and relationships above, I want to have a page that displays a member object and the one member status history object that does not have an end date. If the user changes the fields on the page for the member status history, I want to take that information and make a new member status history object and save that to the member_status_histories in member.
I have tried several things, but granted that I’m new to RoR, I’m not sure what approach to use to do this. It seems like there are several ways to try to get this to possibly work, but I haven’t been able to get any of them to fully work.
The idea that seemed to make the most sense to me was using a virtual attribute. The virtual attribute would provide the member status history object that I wanted to display, and then when the user submitted the updated member and member status history, I could run some business logic on the virtual attribute (using before_save) and update the *member_status_histories* field as needed.
Again, I have been unable to get any approach to work so I am open to suggestions on how to accomplish this. Thanks!
I’d ditch the concept of multiple MemberStatusHistories. It’ll quickly get very complicated and luckily for you there’s already a gem that does everything you want called paper_trail. In member_status_history.rb:
Then you can do @member.member_status_history.previous_version to see the version before the current member_status_history, and the current one is always the “live” one at @member.member_status_history. That should allow you to always see the “most recent” member status history while constantly having the ability to an arbitrary number of remaining ones from your paper_trail version table.
For more information on how that all works, check out the paper_trail github documentation.