I have a Publication model with a has_many relationship to Contributors. In the model, I have a method that’s meant to create an html-ready by line:
def authors
authors = []
Contributor.where(:publication_id => self.id).each do |author|
authors << "link_to "+author.name+", Contributor.find("+author.id.to_s+")"
end
authors.to_sentence
end
In my view, I have the following line:
by <%= @publication.authors %>
But instead of rendering links, it renders the raw code, such as:
by link_to B, Contributor.find(1)
I’ve tried patching this by adding .html_safe to the end of @publication.authors, but to no avail. Is there a better way to transfer these links from the model to the view?
You’re pushing strings into your
authorsarray. It looks like valid code, so runningevalon it should work. (Actuallyauthor.namewill probably evaluate as an undefined symbol, so scratch that.)A better way would be to use a
has_many :authors, :model => 'Contributor'relationship on yourPublicationmodel, and you can bring up your array ofContributorobjects by simply callingYou’d want to iterate over these in your view like so:
Note also that if you’re displaying multiple
Publicationobjects in a view this way, you’ll want to usePublication.includes(:authors)in your controller when you’re retrieving them to avoid the “N+1” problem.Now, three lines of code doesn’t seem very expensive to repeat, but there are ways to DRY that without violating the MVC pattern and cluttering your model:
Here’s a snippet from the source for
to_sentence(you can adapt it for your needs, I think):The full source can be found here.