I currently have a tagging system in place with the following code
rails g model tag name:string
rails g model tagging post_id:integer tag_id:integer
rake db:migrate
class Tagging < ActiveRecord::Base
belongs_to :post
belongs_to :tag
end
class Tag < ActiveRecord::Base
has_many :taggings, :dependent => :destroy
has_many :posts, :through => :taggings
end
class Post < ActiveRecord::Base
has_many :comments, :dependent => :destroy
has_many :taggings, :dependent => :destroy
has_many :tags, :through => :taggings
validates_presence_of :name, :content
attr_writer :tag_names
after_save :assign_tags
def tag_names
@tag_names || tags.map(&:name).join(' ')
end
private
def assign_tags
if @tag_names
self.tags = @tag_names.split(/\s+/).map do |name|
Tag.find_or_create_by_name(name)
end
end
end
end
<p>
<%= f.label :tag_names %><br />
<%= f.text_field :tag_names %>
</p>
in the _post.html.erb partial
I am trying to call a post with a specific tag by doing
<%= post.find_by_tag("sports") %>
When I do this all the posts with the tag come up which is what I want but they come up in this format
[#<Post id: 11, title: "adfads", body: "adsfasd", user_id: 1, created_at: "2012-05-30 06:17:52", updated_at: "2012-05-30 06:17:52", votes_count: 1>, #<Post id: 8, title: "Cover Letter", body: "Dear Human Resources:\r\n\r\nI would like to make mysel...", user_id: 1, created_at: "2012-05-30 00:28:56", updated_at: "2012-05-30 00:28:56", votes_count: 1>]
How can I make them come up in a more agreeable fashion of post title post body instead of what it is rendering right now?
You should really have your find in the controller. Ignoring that issue, try this:
Ideally, you would have
@posts = post.find_by_tag("sports")in the controller, and then loop through @posts instead of my_posts. Format the above as needed.Hope this helps.