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 Categorization model unless there's a use case you haven't described here. You can set up a many-to-many relationship like this:
class Blog < ActiveRecord::Base
has_and_belongs_to_many :categories
end
class Category < ActiveRecord::Base
has_and_belongs_to_many :blogs
end
You should have a database table like this:
class CreateBlogsCategories < ActiveRecord::Migration
def change
create_table :blogs_categories, id: false do |t|
t.references :blog
t.references :category
end
end
end
Then you can construct the view like this:
<div class="field">
Categories:
<% #categories.each do |category| %>
<%= label_tag do %>
<%= check_box_tag 'blog[category_ids][]', category.id, #blog.category_ids.include?(category.id) %>
<%= category.name %>
<% end %>
<% end %>
</div>
Lastly, in your form_for, you specify url: blogs_path - you should remove this if you plan to use this form for the edit action as well, because that should generate a PUT request to /blogs/:id. Assuming you used resources :blogs in routes.rb, Rails will determine the correct path for you based on the action used to render the form.
Related
i need your help to create parent-child relation.
i have a problem to make the create of the child working fine.
this is the model:
class Nccheklist < ActiveRecord::Base
has_many :children, class_name: "Nccheklist", foreign_key: "parent_id"
belongs_to :parent, class_name: "Nccheklist"
def has_parent?
parent.present?
end
def has_children?
children.exists?
end
end
the controller:
def create
#nccheklist = Nccheklist.new(nccheklist_params)
if #nccheklist.save
redirect_to nccheklists_url, notice: 'Nccheklist was successfully created.'
else
render :new
end
end
and the view :
<%= form_for(#nccheklist) do |f| %>
<% if #nccheklist.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#nccheklist.errors.count, "error") %> prohibited this nccheklist from being saved:</h2>
<ul>
<% #nccheklist.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div>
<%= f.collection_select(:parent_id, #rootcat, :id, :name) %>
</div>
<br/><br/>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
when i submit the form, parent_id always equal null on database !
can someone help me please.
thanks.
add the following to the class definition
accepts_nested_attributes_for :children, allow_destroy: true
I am trying to get a Project form to build the first (starting) time of several (up to 12) volunteer time blocks.
project.rb
class Project < ActiveRecord::Base
attr_accessible :title, ...
has_many :vol_times, :dependent => destroy
accepts_nested_attributes_for :vol_times, :reject_if => lambda { |a| a[:start_time].blank? }, :allow_destroy => true
...
end
vol_time.rb
class Vol_time < ActiveRecord::Base
attr_accessible :start_time, ...
belongs_to :project
end
ProjectsController
class ProjectsController < ApplicationController
before_filter :signed_in_user, only: :create
...
def new
#project = Project.new
#user = current_user
#project.vol_times.build
end
...
end
Vol_Times Controller
class Vol_TimesController < ApplicationController
def new
#reward = Reward.new
end
...
end
My view looks like this...
<%= form_for(#project) do |f| %>
<div class="form_field_block">
<p class="form_label"> Project Title</p>
<%= f.text_field :title, :size => 40, :placeholder => " Project Title...", :class => "frm" %>
</div>
<div class="form_field_block">
<p class="form_label"> Project Sub-title</p>
<%= f.text_field :sub_title, :size => 40, :placeholder => " Project Sub-title...", :class => "frm" %>
</div>
<p class="clearing"></p>
<div class="form_field_block">
<% f.fields_for :vol_times do |builder| %>
<%= render :partial => 'start_time', :f => builder %>
<% end %>
</div>
<p class="clearing"></p>
<%= button_tag "btn_start_project.png", :class => "btn_save" %>
<% end %>
And the _partial looks like this...
<%= f.label :start_time, "Starting Time" %>
<%= f.text_field :start_time %>
When I view the page, I see the containing <div>, but not the contents of the ERB, which should be parsed from the _partial.
Any ideas why this isn't working? I got the general context from Ryan Bates' RailsCast #196 - Here
you are missing a = on the fields_for. It should be
<%= f.fields_for :vol_times do |builder| %>
I have a model that has amenities with a 1:1 relationship:
class Listing < ActiveRecord::Base
attr_accessible :address1, :address2, :bath, :bedroom, :city, :description, :neighborhood, :sleeps, :sqft, :state_id, :title, :zip, :images_attributes, :amenity_attributes
has_many :images, :dependent => :destroy
accepts_nested_attributes_for :images, :allow_destroy => true
has_one :amenity
accepts_nested_attributes_for :amenity, :allow_destroy => true
end
And Amenities table:
class Amenity < ActiveRecord::Base
attr_accessible :air_conditioning, :balcony
belongs_to :listing
end
Lastly, my view:
<%= simple_nested_form_for (#listing), :html => {:multipart => true} do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :title %>
<%= f.input :sleeps %>
<%= f.input :bath %>
<%= f.input :bedroom %>
<%= f.input :sqft %>
<%= f.input :neighborhood %>
<%= f.input :address1 %>
<%= f.input :address2 %>
<%= f.input :city %>
<%= f.input :state_id %>
<%= f.input :zip %>
<%= f.input :description %>
</div>
<!-- amenities -->
<%= f.fields_for :amenities do |a| %>
<div class="amenities">
<label><%= a.check_box :smoking %> Smoking Allowed</label>
</div>
<% end %>
<!-- end amenities -->
<!-- Submit button -->
<% end %>
When I hit submit I get the error:
Can't mass-assign protected attributes: amenities
Any idea what's up here? It won't submit even though I allow :amenities_attributes and accepts_nested tags.
You have a has_one association so amenities should not be plural.
change
<%= f.fields_for :amenity do |a| %>
EDIT
<%= f.fields_for :amenity do |a| %>
<div class="amenities">
<%= a.label :smoking, 'Smoking Allowed' %>
<%= a.check_box :smoking %>
</div>
<% end %>
<p><%= f.submit "Submit" %></p>
<% end %>
Also, checkout this documentation for a one to one association, http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
Fixed:
class Listing < ActiveRecord::Base
has_one :amenity
accepts_nested_attributes_for :amenity
after_initialize do
self.amenity ||= self.build_amenity()
end
end
i have many to many throught asociation and then i do this
fields_for :device
this displaying in good way, but i cannot save it i get unknown attribute :price
And fields_for :devices
And so on, one device makes one more repeat, if i write f.fields_for :price it gives good text field count, but it write
unknown attribute: price
Rails.root: C:/Users/Ignas/mildai/baze4
Application Trace | Framework Trace | Full Trace
app/controllers/commercial_offers_controller.rb:74:in `block in update'
app/controllers/commercial_offers_controller.rb:73:in `update'
thank you
additional information:
controller
def edit_prices
#commercial_offer = CommercialOffer.find(params[:id])
end
link to edit prices
<%= link_to "Edit prices", :controller => "CommercialOffers", :action => "edit_prices", :id => #commercial_offer %>
_edit_price.html.erb
<%= form_for #commercial_offer do |f| %>
<% CommercialOffer.find(params[:id]).devices.each do |device| %>
<%= check_box_tag "commercial_offer[device_ids][]", device.id, #commercial_offer.devices.include?(device) %>
<%= device.name %>
<%= f.fields_for :prices do |builder| %>
<%= render 'prices/new_price', :f => builder, :commercial_offer => #commercial_offer, :device => device %>
<% end %>
<% end %>
<div class="actions">
<%= f.submit "Save"%>
</div>
<% end %>
for one device it have render only one time, but it rendering for one device such times how many devices is with same commercial_offer_id
_new_price.html.erb
Price:
<%= f.text_field :price %></br>
Quantity:
<%= f.text_field :quantity %></br>
Device id:
<%= f.text_field :device_id, :value => device.id %></br>
class CommercialOffer < ActiveRecord::Base
has_many :prices
has_many :devices, :through => :prices
accepts_nested_attributes_for :prices
accepts_nested_attributes_for :devices
end
class Device < ActiveRecord::Base
has_many :prices
accepts_nested_attributes_for :prices
has_many :commercial_offer, :through => :prices
class Price < ActiveRecord::Base
belongs_to :device
belongs_to :commercial_offer
end
There is no any field_for method.
Also your question isn't clear. What actually you want to do? Show only one device? Wich one? First, last?
UPD
commercial_offer.rb:
class CommercialOffer < ActiveRecord::Base
has_many :prices
has_many :devices, :through => :prices
accepts_nested_attributes_for :prices
accepts_nested_attributes_for :devices, :allow_destroy => true
end
Your view
<%= form_for #commercial_offer do |f| %>
<%= f.fields_for :devices do |device| %>
<p>
<%= device.check_box :_destroy %>
<%= device.label "Destroy?" %>
</p>
<p>
<%= device.text_field :name %>
</p>
<%= device.fields_for :prices do |builder| %>
<%= render 'prices/new_price', :f => device %>
<% end %>
<% end %>
<% end %>
<div class="actions">
<%= f.submit "Save"%>
</div>
<% end %>
_new_price partial
<%= f.text_field :price %></br>
Quantity:
<%= f.text_field :quantity %></br>
Device id:
<%= f.text_field :device_id %></br>
I'm tring to set values for two models that have a has_one association using accepts_nested_attributes_for, but nothing in the fields_for is being shown on the view.
I have confirmed the same code works on Rails 2.x, and it works fine when its a has_many.
Code below.
Model
class Parent < ActiveRecord::Base
has_one :child
accepts_nested_attributes_for :child
end
class Child < ActiveRecord::Base
belongs_to :parent
end
Controller
def new
#parent = Parent.new
#parent.build_child
end
View
<%= form_for #parent do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<% f.fields_for :child do |builder| %>
<%= builder.label :childname %>
<%= builder.text_field :childname %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
..And after copying that and looking at it, that's a horrible class name.
In rails 3 you should use (notice the equal sign in <%=):
<%= f.fields_for [...]
instead of :
<% f.fields_for
same goes with form_for