rails how get related id on view page - ruby-on-rails

i'm trying to make this conditional:
<% if current_boutique.boutique_kind(3) %>
Brand: <span><%= current_boutique.name %></span>
<% else %>
<%= p.input :brand_id, :as => :select, :collection=> Brand.find(:all, :order=>:name).collect{ |b| [b.name,b.id, b.name]},
:label => "Marca", :prompt => 'Select Brand', :required => true %>
<% end %>
but the boutique_kind(3) show all boutiques! how i just get the boutiques with boutiques_kind id 3 method!
boutiqueKind Controller
def show
#boutique_kind = BoutiqueKind.find(params[:id])
end
boutiqueKind model
attr_accessible :kind, :slug
has_many :boutiques
has_many :products, :through => :boutiques
#belongs_to :gender
accepts_nested_attributes_for :boutiques
attr_accessible :boutiques, :boutiques_attributes, :kind
Boutique Controller
class Boutique < ActiveRecord::Base
belongs_to :user
belongs_to :boutique_kind
end

You should be able to find the boutique by ID with:
BoutiqueKind.find(3)
If I'm misunderstanding, and id is not a unique id (in which case I suggest you rename the column to something other than id), you can get all records where a certain field == a specific value with:
BoutiqueKind.where(id: 3)

Related

Couldn't find Manufacturer with 'id'= (blank)

I am trying to create a web application to practise my Ruby on Rails skill. I have a few entities in my database manufacturers, models, tints, prices
manufacturers {id, name} - stores the make of the car
models {id, manufacturer_id, name} - stores the models of the car
tints {id, manufacturer_id, model_id, front, sides, rear} - stores the length of tint required
prices {id, description, price } - stores the price of the item
I created a page to generate a quotation for window tinting. The page includes drop-down menus to let user to select manufacturer, model, type of film(front), type of film(side+rear)
Below is the code for the form
<%= form_tag('/quotation/tints/generate') do %>
<%= label :manufacturer_id, 'Manufacturer' %>
<div class="field">
<%= collection_select(:tint, :manufacturer_id, Manufacturer.order(:name), :id, :name, {:prompt => "Select Manufacturer"}) %>
</div>
Model:
<div class="field">
<%= grouped_collection_select(:tint, :model_id, Manufacturer.order(:name), :models, :name, :id, :name, {:prompt => "Select Model"}) %>
</div>
<%= label :price_front, 'Front Tint' %>
<div class="field">
<%= collection_select(:price, :price_front, Price.order(:name), :id, :name, {:prompt => "Select Front Tint"}) %>
</div>
<%= label :price_rear, 'Size and Back Tint' %>
<div class="field">
<%= collection_select(:price, :price_rear, Price.order(:name), :id, :name, {:prompt => "Select Side & Rear Tint"}) %>
</div>
<div class="form-group">
<%= submit_tag 'Submit' %>
</div>
<% end %>
When the form is submitted, it should be redirected to /quotation/tints/generate and display the value from the dropdown menu. However, I received an error, saying that Couldn't find Manufacturer with 'id'=. The code that caused the error is shown below
def generate
#manufacturers = Manufacturer.find(params[:manufacturer_id])
end
Here is the parameter from the debug log
{"utf8"=>"✓",
"authenticity_token"=>"Pl2bXiRT0AoF4i0h1RCHDbuvaKJNZOkV5ULQHKxDQgZzBWWLJ2mH7ddb9akwgxbloxBIHoVaT3pcwoIGcRufpg==",
"tint"=>{"manufacturer_id"=>"7", "model_id"=>"6"},
"price"=>{"price_front"=>"1", "price_rear"=>"2"},
"commit"=>"Submit"}
I can see that the id of each drop down value are shown up correctly in the parameter list. However, I coundn't able to print the value at /quotation/tints/generate nor get the name of the manufacturer or model.
Here is routes.rb:
get '/quotation/tints' => 'tints#quotation', :as => 'tints_quotation'
post '/quotation/tints/generate' => 'tints#generate', :as => 'generate_tints_quotation'
Tint.rb:
class Tint < ApplicationRecord
has_many :manufacturers
has_many :models
belongs_to :manufacturer
belongs_to :model
validates_uniqueness_of :model_id, :scope => [:manufacturer_id]
end
Model.rb:
class Model < ApplicationRecord
belongs_to :manufacturer, :dependent => :destroy
validates :name, :presence => true
validates_uniqueness_of :name, :scope => [:manufacturer_id]
before_save :capitalize_content
end
Manufacruter.rb:
class Manufacturer < ApplicationRecord
has_many :models, :dependent => :destroy
validates :name, :presence => true, uniqueness: { case_sensitive: false }
before_save :capitalize_content
end
tints.controller.rb:
def quotation
render 'quotation'
end
def generate
#manufacturers = Manufacturer.find(params[:manufacturer_id])
end
generate.html.erb:
<%= #manufacturers.name %>
I'm trying to print the manufacturer selected
I have tried multiple ways to define it, but I am still facing the same error. Any help is greatly appreciated.
In your params, manufacturer_id is a nested value of tint, as opposed to being a direct key of the params hash. Try the following:
def generate
#manufacturers = Manufacturer.find(params[:tint][:manufacturer_id])
end

Rails nested form with has_many :through, not saving the data to joining table

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?

Has Many Through Checkboxes Not Saving Values Rails3

I've set up a has_many through relationship in my db and changed the keys because I'm working with a legacy db.
It all seems to be working but I cannot get the checkboxes to save to the database.
My models are as follows:
class Radcheck < ActiveRecord::Base
set_table_name 'radcheck'
attr_accessible :attribute_name, :username, :value, :op, :groupname
belongs_to :raduser
has_many :radusergroup, :dependent => :destroy, :primary_key => :username, :foreign_key => :groupname
has_many :radgroupcheck, :through => :radusergroup
end
class Radgroupcheck < ActiveRecord::Base
set_table_name 'radgroupcheck'
has_many :radusergroup, :dependent => :destroy#, :primary_key => :groupname, :foreign_key => :username
has_many :radcheck, :through => :radusergroup
end
class Radusergroup < ActiveRecord::Base
belongs_to :radcheck, :foreign_key => 'groupname', :primary_key => 'username'
belongs_to :radgroupcheck, :foreign_key => 'username', :primary_key => 'groupname'
end
In my form, I have this:
<% Radgroupcheck.all.each do |group| -%>
<%= check_box_tag :groupnames, group.id, #radcheck.radgroupcheck.include?(group), :username => 'radcheck[groupname][]' -%> | <%= label_tag :groupnames, group.groupname -%>
<% end -%>
The form renders the checkboxes ok and I can see the groupnames but nothing happens when I hit save.
The development log is clear and I can't see anything in the mysql query log either.
Try using this in your form:
<% Radgroupcheck.all.each do |group| -%>
<%= check_box_tag "radcheck[radgroupcheck_ids][]", radgroupcheck.id, #radcheck.radgroupchecks.include?(radgroupcheck), :id => "radcheck_radgroupcheck_id_#{radgroupcheck.id}" -%>
<%= label_tag "radcheck[radgroupcheck_ids][]", radgroupcheck.name, :for => "radcheck_radgroupcheck_id_#{radgroupcheck.id}" -%>
<% end %>
And in your controller:
def create
params[:radcheck][:radgroupcheck_ids] ||= []
#radcheck = Radcheck.new(params[:radcheck])
# rest of your controller logic
end
This is adapted from what worked for me in a Rails 3.1 project, based on http://railscasts.com/episodes/17-habtm-checkboxes?view=asciicast

Rails has_many :through and collection_select with multiple

I have the following problem using a has_many :through many-to-many relation in a multi-select via collection_select :multiple => true. I have Suppliers who deliver many Ingredients which can be delivered by many Suppliers. Have a look:
The Ingredient model:
class Ingredient < ActiveRecord::Base
has_many :ingredient_suppliers
accepts_nested_attributes_for :ingredient_suppliers, :allow_destroy => true
has_many :suppliers, :through => :ingredient_suppliers
end
The Supplier model:
class Supplier < ActiveRecord::Base
has_many :ingredient_suppliers
has_many :ingredients, :through => :ingredient_suppliers
end
The relationship Entity:
class IngredientSupplier < ActiveRecord::Base
belongs_to :ingredient
belongs_to :supplier
end
And this is the form. Note that I could not get it to work without specifying the :name:
<%= form_for(#ingredient) do |f| %>
<%= f.fields_for :suppliers do |supplier_fields| %>
<%= supplier_fields.collection_select (:supplier_ids,
Supplier.all(:order=>"name ASC"),
:id, :name,
{:selected => #ingredient.supplier_ids,
:include_blank => true},
{:multiple => true,
:name => 'ingredient[supplier_ids]'}) %>
<% end %>
<% end %>
If I remove the :name, then I get this error message:
Supplier(#-617951108) expected, got Array(#-608411888)
Request
Parameters:
{"commit"=>"Anlegen",
"authenticity_token"=>"MuEYtngwThharmM1KaAbH8JD3bScXiDwj0ALMytxl7U=",
"_method"=>"put",
"utf8"=>"✓",
"id"=>"1",
"ingredient"=>{"name"=>"Ingredient 1",
"nr"=>"00100",
"unit"=>"kg",
"mol_per_unit"=>"2000,
00000",
"description"=>"",
"suppliers"=>{"supplier_ids"=>["1",
"2"]}}}
The problem now is, that the PUT parameters only contain one supplier_id instead of an array of supplier_ids:
"ingredient"=>{"name"=>"Rohstoff 3", "nr"=>"00300", "unit"=>"Stk.", "mol_per_unit"=>"0,00000", "description"=>"", "supplier_ids"=>"2"}
I've got the problem solved. In this case, using fields_for was the error. The solution is using a collection_select, like this:
<%= collection_select(:ingredient, :supplier_ids,
Supplier.all(:order=>"name ASC"),
:id, :name, {:selected => #ingredient.supplier_ids, :include_blank => true}, {:multiple => true}) %>

Assigning a nested attribute with Formtastic

I've been trying to figure this one out for a while but still no luck. I have a company_relationships table that joins Companies and People, storing an extra field to describe the nature of the relationship called 'corp_credit_id'. I can get the forms working fine to add company_relationships for a Person, but I can't seem to figure out how to set that modifier field when doing so. Any ideas?
More about my project: People have many companies through company_relationships. With that extra field in there I am using it to group all of the specific relationships together. So I can group a person's Doctors, Contractors, etc.
My models:
Company.rb (abridged)
class Company < ActiveRecord::Base
include ApplicationHelper
has_many :company_relationships
has_many :people, :through => :company_relationships
Person.rb (abridged)
class Person < ActiveRecord::Base
include ApplicationHelper
has_many :company_relationships
has_many :companies, :through => :company_relationships
accepts_nested_attributes_for :company_relationships
company_relationship.rb
class CompanyRelationship < ActiveRecord::Base
attr_accessible :company_id, :person_id, :corp_credits_id
belongs_to :company
belongs_to :person
belongs_to :corp_credits
end
My form partial, using formtastic.
<% semantic_form_for #person do |f| %>
<%= f.error_messages %>
<% f.inputs do %>
...
<%= f.input :companies, :as => :check_boxes, :label => "Favorite Coffee Shops", :label_method => :name, :collection => Company.find(:all, :conditions => {:coffee_shop => 't'}, :order => "name ASC"), :required => false %>
So what I would like to do is something like :corp_credit_id => '1' in that input to assign that attribute for Coffee Shop. But formtastic doesn't appear to allow this assignment to happen.
Any ideas on how to do this?
Are you looking for something like
<% semantic_form_for #person do |form| %>
<% form.semantic_fields_for :company_relationships do |cr_f| %>
<%= cr_f.input :corp_credit_id %>
<% end %>
It is in the documentation

Resources