A Rails 4.2 app has three models:
- User
- Author
- Quote
... and the following associations:
- users HABTM authors
- author has_many quotes
If the user is associated with any authors, his "profile" view should display statistics about the number of quotes of each author.
Example:
Your author(s) Mark Twain has 73 quotes, Charles Dickens has 92 quotes, and Oscar Wilde has 53 quotes.
If the user is not associated with any authors, that same view should display a different message.
Within the user model (app/models/user.rb
):
def authors_statistics
statistics = Array.new
self.authors.each do |author|
statistics << "#{author.name} has #{author.quotes.count} quotes"
end
statistics.to_sentence
end
Within the user profile view (ERB):
<% if current_user.authors_statistics.empty? %>
You have not yet been given access to edit any authors' quotes. Please
<%= link_to 'send us a message', new_contact_form_path %> specifying to
whose authors quotes you would like to contribute.
<% else %>
Your author(s) <%= current_user.authors_statistics %>
<% end.to_sentence %>.
It seems to me that there is excessive coupling between the model and the view. Can you think of a better way to do it?