dimanche 1 février 2015

add Taggings record to Post and Tag with Rails 4 nested form

I have 3 models, Post, Tag and Taggings and I am trying to build a form to create the taggings through an array of checkboxes. I can't seem to get ANY of the Tagging records to save (even though it



<%= form_for @post %>
<%= hidden_field_tag "post[tag_ids][]", nil %>
<% Tag.colors.each do |tag| %>
<%= check_box_tag "post[tag_ids][]", tag.id, @post.tag.include?(tag), id: dom_id(tag)
%>
<%= label_tag dom_id(tag), tag.name %><br>
<% end %>
<label>Post title</label>
<%= text_field :title %>

<%= submit_tag 'ADD TAGS' %>


Controller



class PostsController < ApplicationController

def add_taggings
@post = Post.find(params[:id])
@taggings = Tagging.new
if @post.update_attributes(post_params)
redirect_to @Post
flash[:notice] = "Successfully Tagged

else
render :edit
end
end

def post_params
params.require(:post).permit( :id, :title, :img, :content, :author,
taggings_attributes:[:id, :post_id, :tag_id, {:tags => []}, {:posts => []}, :_destroy])


Models



class Post < ActiveRecord::Base
has_many :taggings

class Tag < ActiveRecord::Base
has_many :taggings

class Tagging < ActiveRecord::Base
belongs_to :tag
belongs_to :post
validates_uniqueness_of :tag, :scope => :post_id




Aucun commentaire:

Enregistrer un commentaire