Reputation: 2581
I spent a lot of time on this one and now I am stuck. I am currently trying to setup a tagging system in my app. I believe all my associations are correct, however I am having trouble with my views. The tags are being created using their own form. What I want to do is when a user creates a new item, they will be able to choose from a list of tags that they have created from the tag form.
Here are my models:
class Item < ActiveRecord::Base
attr_accessible :title, :media, :tag_ids
belongs_to :user
has_many :taggings, :dependent => :destroy
has_many :tags, :through => :taggings
end
class Tag < ActiveRecord::Base
attr_accessible :name
belongs_to :user
has_many :taggings, :dependent => :destroy
has_many :items, :through => :taggings
end
Here are my views which I know are flawed. Item form:
<%= form_for @item, :html => { :multipart => true } do |f| %>
<div class="field">
<%= f.file_field :media %>
<%= f.text_field :title, placeholder: "Add title..." %>
<% @tags.each do |tag| %>
<div>
<%= check_box_tag "item[tag_ids][]", tag.id, @item.tags.include?(tag) %>
<%= tag.name %>
</div>
<% end %>
</div>
Show item view:
<li>
<span class="title"><%= item.title %></span>
<%= image_tag item.media.url(:small) %>
<span>
<% @item.tags.each do |tag| %>
<% tag.name %>
<% end %>
</span>
<span class="timestamp">
Posted <%= time_ago_in_words(item.created_at) %> ago.
</span>
<%= link_to "delete", item, method: :delete, confirm: "You sure?", title: item.title %>
</li>
The tags are being created and both items and tags are being attached properly in my taggings database. However, I need help with two things:
I'm also new to Rails and want to learn how to do this without a plugin.
Upvotes: 1
Views: 376
Reputation: 2581
I finally figured it out. The show-item code that I posted is actually a partial. In the view that references the partial, I am using <% render @item %>
. So in my tag loop, it should be
<span>
<% item.tags.each do |tag| %>
...
not @item.tags.each |tag| %>
Upvotes: 0
Reputation: 9018
@tags
in your controller.you're probably setting it like this
@tags = Tag.all
Change it to
@tags = current_user.tags
Here I'm presuming that your Devise model is called User. You might also have to take some precautions since you're now showing tags for authenticated users only.
<% tag.name %>
with <%= tag.name %>
.Upvotes: 1