Skip to content

Instantly share code, notes, and snippets.

@adamdawkins
Created June 10, 2011 16:28
Show Gist options
  • Save adamdawkins/1019214 to your computer and use it in GitHub Desktop.
Save adamdawkins/1019214 to your computer and use it in GitHub Desktop.
'find or create by' Rails
<%= form_for(@quote) do |f| %>
<% if @quote.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@quote.errors.count, "error") %> prohibited this quote from being saved:</h2>
<ul>
<% @quote.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :text, "Quote:" %><br />
<%= f.text_area :text %>
</div>
<div class="field">
<%= f.label :author %><br />
<%= f.text_field :author %>
</div>
<div class="field">
<%= f.label :source %><br />
<%= f.text_field :source %>
</div>
<div class="field">
<%= f.label :tag_names, "Tags" %><br />
<%= f.text_field :tag_names %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
class Quote < ActiveRecord::Base
has_many :taggings, :dependent => :destroy
has_many :tags, :through => :taggings
after_save :assign_tags
attr_accessor :tag_names
def tag_names
@tag_names || tags.map(&:name).join(', ')
end
private
def assign_tags
if @tag_names
self.tags = @tag_names.split(/,+/).map do |name|
Tag.find_or_create_by_name(name)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment