I have a form for creating a Style. When creating the style the user must also choose some features for the style.
The features are pre-populated into a multi-select box inside the form. When the style is saved the through table should be updated with entries (with style_id and feature_id) for each feature selected on the form.
I have in my controller:
def new
#style = Style.new
#style.stylefeatures.build
end
def create
#style = Style.new(params[:style])
#style.stylefeatures.build
#style.save
end
...and in my style model
attr_accessible :stylefeatures_attributes
has_many :stylefeatures
has_many :features, :through => :stylefeatures, :foreign_key => :feature_id
accepts_nested_attributes_for :stylefeatures
... and in my stylefeature model
belongs_to :style
belongs_to :feature
accepts_nested_attributes_for :feature
... and in my feature model
attr_accessible :description, :fullname, :name
has_many :stylefeatures
has_many :styles, :through => :stylefeatures, :foreign_key => :style_id
... and in my create form
<%= m.simple_fields_for :stylefeatures do |p| %>
<%= p.input :feature_id, :label => "Features", :collection => Feature.all, :input_html => { :multiple => true } %>
<% end %>
Now when I save the new Style, the stylefeatures table is updated with the appropriate style_id, but with two useless entries. The first is an array with all of the feature ids which have been selected in the form. The second is a blank entry with the appropriate style_id and nothing in the feature_id column.
Do you have any clue of what I might be doing wrong, or how to spread the collected feature_id's into the table as desired?
in new action u r building only one stylefeature, so only one will be created with feature_id = '1,3,45,563' (ofc depends that features u selected)
second one is generated by #style.stylefeatures.build in create action
u can try to remove fields_for and simply use :feature_ids instead of :feature_id
<%= p.input :feature_ids, :label => "Features", :collection => #features, :input_html => { :multiple => true } %>
or
<%= input_tag "style[feature_ids][]" , :label => "Features", :collection => #features, :input_html => { :multiple => true } %>
Related
I have a nested form inside a parent form that allows you to add fields inside the parent form. The idea is that a book can have many schools and the school belongs to the book(habtm) relationship. here are my models:
books.rb
accepts_nested_attributes_for :author
accepts_nested_attributes_for :gallery, :allow_destroy => true
accepts_nested_attributes_for :schools, :reject_if => :find_school, :allow_destroy => true
accepts_nested_attributes_for :images, :allow_destroy => true
def find_school(school)
if existing_school = School.find_by_school_name(school['school_name'])
self.schools << existing_school
return true
else
return false
end
end
school.rb
class School < ActiveRecord::Base
has_and_belongs_to_many :books
validates :school_name, :address, presence: true
#validates_uniqueness_of :school_name
end
In my form for the book I have this setup:
<div id="school" class="field">
<h3>Schools reading this book (add the name and full address of the school)</h3>
<%= f.simple_fields_for :schools, :wrapper => 'inline' do |builder| %>
<%= render 'school_fields', :f => builder %>
<%= link_to_add_association 'add school', f, :schools, :render_options => {:wrapper => 'inline' }, :class => 'fa fa-plus' %>
<% end %>
</div>
In here it should render the fields but I get this
The issue i have is that in my book.rb model the find_school method keeps returning multiple values of the same books when I update the book. The idea is that the find_school method basically stops duplicate schools being created as records and just assigns them as a relationship to the book instead. What I am finding is that this self.schools << existing_school on update just keeps duplicating the fields in the edit form and adds the fields as entries on the item when I check in the params output.
Can anyone help with this
I want to add a collection_select from a form I want to be within another form.
I have a Product model, with:
has_many :distribution_companies
has_many :distributors, :through => :distribution_companies, :source => :company
and Company model, with:
has_many :distribution_companies
has_many :distributed_products, :through => :distribution_companies, :source => :product
(The distribution_companies has only the references to the mentioned models)
This is the form (don't pay attention on the indentation):
= form_for #product, html: { :multipart => true } do |f|
= f.label :name do
Name
= f.text_field :name
/.../
= f.fields_for :distribution_companies do |pn|
= pn.collection_select :company_id, Company.all, :id, :name
= f.submit 'Create the product'
I need to add select a company for the #product and store that in the distribution_companies table. I tried as abowe (also with pn.object.coll...). Any idea?
As i said ,you have to add #product.distribution_companies.build to the new method of our controller.
def new
#product = Product.new
#product.distribution_companies.build
end
I am kinda new to Rails and this is my first post to StackOverflow.
Say I have 3 models:
class Product < ActiveRecord::Base
default_scope :order => :title
has_many :line_items
has_many :promo_products
has_many :promotions, :through => :promo_products, :foreign_key => :promotion_id
before_destroy :ensure_not_referenced_by_any_line_item
before_destroy :ensure_not_referenced_by_any_promo_product
validates :title, :presence => true, :uniqueness => true
validates :description, :presence => true
validates :price, :numericality => {:greater_than_or_equal_to => 0.01}
private
def ensure_not_referenced_by_any_line_item
if line_items.empty?
return true
else
errors.add(:base, 'Line Items present')
return false
end
end
def ensure_not_referenced_by_any_promo_product
if promo_products.empty?
return true
else
errors.add(:base, 'Some promotions are still in effect')
return false
end
end
end
class Promotion < ActiveRecord::Base
CART_OR_PRODUCT = ['Cart', 'Product']
PROMOTION_TYPE = ['Percentage based', 'Value based']
has_many :promo_products
accepts_nested_attributes_for :promo_products
has_many :products, :through => :promo_products, :foreign_key => :product_id
accepts_nested_attributes_for :products
#attr_accessible :promo_products_attributes, :title, :description, :cart_or_product, :promotion_type, :discount, :minimum_price, :minimum_quantity
validates :title, :description, :presence => true
validates :cart_or_product, :inclusion => {:in => CART_OR_PRODUCT, :message =>
"is invlaid. Please select a valid option"}
validates :promotion_type, :inclusion => {:in => PROMOTION_TYPE, :message =>
"is invalid. Please select a valid option"}
validates :discount, :minimum_price, :numericality => {:greater_than_or_equal_to => 0.00}
validates :minimum_quantity, :numericality => {:greater_than_or_equal_to => 0}
end
class PromoProduct < ActiveRecord::Base
belongs_to :promotion
belongs_to :product
accepts_nested_attributes_for :products
end
In the promotions new page, I would like to show list of products that could be part of a promotion. A user may select 0, 1 or more products, depending on the type of promotion.
In the action new of promotions_controller, I built like this:
#promotion.promo_products.build.build_product
In the _form of promotions, I needed to show the list of products for user to select. I made a nested form like:
<%= form_for(#promotion) do |f| %>
<!-- other promotion fields -->
<%= f.fields_for :promo_products do |pp| %>
<%= pp.fields_for :products do |p| %>
<div class="field">
<%= f.label "Products" %><br />
<%= collection_select :promo_product, :product_id, Product.all, :id, :title {:selected => #promotion.product_ids}, {:multiple => true} %>
</div>
<% end %>
<% end %>
<% end %>
I have 2 issues.
First my code throws an error:
ArgumentError in PromotionsController#new
No association found for name `products'. Has it been defined yet?
If I change the line in PromoProduct model:
accepts_nested_attributes_for :products
to
accepts_nested_attributes_for :product
Then there are no errors, and everything works fine.
The data doesn't get saved to promo_product table. I have the create action in promo_product controller as:
def create
#promotion = current_promotion
products = Product.select(:id => params[:product_id])
products.each do |p|
promo_product = #promotion.promo_products.build(p)
promo_product.save
end
##promo_product = PromoProduct.new(params[:promo_product])
redirect_to promotions_path
end
How can I go about it?
Thank you.
You shouldn't put the "accept_nested_attribute_for" in the association table PromoProducts. It should exist in the model that you want to use for creating association to another model. "accept_nested_attribute_for" IIRC simply inserts an "[association]_attributes=" method for your model. For instance, if you add this method to your Product class for Promotion, you will get "promotion_attributes=" method inserted in the Product class. Then a nested form can use this function to create new objects with a hash that represents the model and association.
Base on the above, the create action shouldn't be in PromoProduct controller, instead it should be in Promotion controller.
<%= form_for(#promotion) do |f| %>
<!-- other promotion fields -->
<%= f.fields_for :products do |pp| %>
<div class="field">
<%= f.label "Products" %><br />
<%= collection_select :promo_product, :product_id, Product.all, :id, :title {:selected => #promotion.product_ids}, {:multiple => true} %>
</div>
<% end %>
<% end %>
I don't know without trying if the above collection_select line is correct. But you can debug this by checking the parameter returned by the form to the controller in the server console log. Basically you should see a nested hash of
{:promotion => {:products => ...}}
Let me know if you need more help on this. In my solution I used a combination of select_tag and options_from_collection_for_select. (But I don't recall the behavior of all these offhand without looking at the API doc.)
Lastly, do you need the :through model? I think since you created the through model you need to handle saving that in your create action. But since you don't have other attributes on the PromoProducts table I wonder if you want to simply leave it as a HABTM association and let rails deal with the rest?
I have this structure models
class Tournament < ActiveRecord::Base
AGES = ["5u", "6u", "7u", "8u"]
has_many :courts, :dependent => :destroy
accepts_nested_attributes_for :courts, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
class Court < ActiveRecord::Base
belongs_to :tournament, :autosave => true
has_many :ages, :dependent => :destroy
accepts_nested_attributes_for :ages, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
class Age < ActiveRecord::Base
belongs_to :court
Now my forms look like this
_form.html.erb
<%= semantic_form_for #tournament do |f| %>
<%= f.inputs do %>
<%= f.input :name, :hint => "What is the name of the Tournament?" %>
<%= f.semantic_fields_for :courts do |builder| %>
<%= render :partial => "court_fields", :locals => { :f => builder } %>
<% end %>
_court_fields.html.erb
<div class="nested_fields">
<%= f.input :name, :input_html => {:class => "name"} %>
<%= f.semantic_fields_for :ages do |builder| %>
<%= render :partial => "age_fields", :locals => { :f => builder } %>
<% end %>
_age_fields.html.erb
Testing ...am I getting in here
<%= f.input :name, :as => :check_boxes, :collection => Tournament::AGES, :input_html => {:class => "age_limits"} %>
everything seems to work well except nothing shows up in the ages_fields partial...not the checkboxes and not even the dummy text Testing ...am I getting in here is not displaying....any ideas what could be causing the issue
The obvious reason I can think of: are you sure your Court has ages ?
[EDIT] That the Court has the relation was indeed clear to me.
But your code will only show an age for a court if it already exists.
From your output in the comments: the court has no actual ages so no ages are shown.
If you do this in your controller:
def new
#tournament = Tournament.new
#tournament.courts.build
#tournament.courts[0].ages.build
end
This will make sure that you have at least one (empty) court and one (empty) age.
Otherwise you could also consider using a gem like cocoon to dynamically add new elements if needed.
Hope this helps.
New formtastic user here.
I have a relationship user has_many clients
In formtastic, if I do something such as
f.input :employer
it returns a select box of all employer object references. I'd like to display (last name, first name) instead. I'm sure this is very simple, but I can't figure out exactly how to do it.. Any help appreciated.
These didnt work for me, however, this did:
<%= f.input :user, :label => "Author", :label_method => :username %>
Also a little cleaner ^^
Or, you can set the display method once and for all on the model itself:
(In employer.rb)
def to_label
email
end
Try
f.input :employers, :as => :select, :collection => Employer.find(:all, :order => "last_name ASC")
or
f.input :employers, :as => :select, :collection => Employer.collect {|e| [e.last_name, e.id] }