I am working on building a blog with categorization. I am a bit stuck on how to implement categorization in the form. I have setup a has many through relationship and want to add check boxes to associate a blog with multiple categories. What I have so far is passing the categories through to the view, and I can list them out, however I cannot get the form_for method working for some reason.
Here is my code.
blog model
class Blog < ActiveRecord::Base
attr_accessible :body, :title, :image
has_many :categorizations
has_many :categories, through: :categorizations
has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }
validates :title, :body, :presence => true
end
Category Model
class Category < ActiveRecord::Base
has_many :categorizations
has_many :blogs, through: :categorizations
attr_accessible :name
end
Categorization Model
class Categorization < ActiveRecord::Base
attr_accessible :blog_id, :category_id
belongs_to :blog
belongs_to :category
end
Blog new controller
def new
@blog = Blog.new
@categories = Category.all
respond_to do |format|
format.html # new.html.erb
format.json { render json: @blog }
end
end
Blog new form view
<%= form_for(@blog, :url => blogs_path, :html => { :multipart => true }) do |f| %>
<% if @blog.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@blog.errors.count, "error") %> prohibited this blog from being saved:</h2>
<ul>
<% @blog.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.file_field :image %>
</div>
<div class="field">
<%= f.label :body %><br />
<%= f.text_area :body %>
</div>
<div class="field">
Categories:
<% @categories.each do |category| %>
<% fields_for "blog[cat_attributes][]", category do |cat_form| %>
<p>
<%= cat_form.check_box :name %>
</p>
<% end %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
This code is my failing point
<% @categories.each do |category| %>
<% fields_for "blog[cat_attributes][]", category do |cat_form| %>
<p>
<%= cat_form.check_box :name %>
</p>
<% end %>
<% end %>
Although I am not positive I am approaching any of it right since I am currently learning. Any advice on how to accomplish this.
Thanks,
CG
First of all, you probably don’t need a separate
Categorizationmodel unless there’s a use case you haven’t described here. You can set up a many-to-many relationship like this:You should have a database table like this:
Then you can construct the view like this:
Lastly, in your
form_for, you specifyurl: blogs_path– you should remove this if you plan to use this form for theeditaction as well, because that should generate a PUT request to/blogs/:id. Assuming you usedresources :blogsin routes.rb, Rails will determine the correct path for you based on the action used to render the form.