Passing value from one model to another using a drop-down menu - ruby-on-rails-3

Models:
product.rb:
class Product < ActiveRecord::Base
attr_accessible :cat_id, :id, :name
belongs_to :category
end
category.rb:
class Category < ActiveRecord::Base
attr_accessible :id, :name
has_many :products
end
Routes:
routes.rb
resources :categories do
resources :products
end
I want to add products to category. What to write in controller and view of product please help!
Please!! I am a beginner to rails!

If you want a drop-down menu:
In _file.html.haml
= label_tag :Category
= select_tag "product[category_id]", options_from_collection_for_select(#categories, :id,:name,#selected = #product[:category_id] :include_blank => true
In products_controller.rb:
before_filter :get_categories, :only => [:new,:edit]
def get_categories
#categories = Category.all
end

You can do as shown below,
If your path(url) should be like http://loaclhost:3000/category/1/produts, use id params from your url
Pass cateogry id into product view
form.erb
<%= f.hidden_field :cat_id , :value => <pass catogory id from routes url> %>
then follow usual create method ( Please inspect object whether cat_id created or not )
Now , you can access category value from cat_id of product.
Hope it will be useful.

Related

Rails: Show data from 2 tables in "collection_select"

I have two models:
class Category < ActiveRecord::Base
attr_accessible :active, :title, :url_name
has_many :category_images
end
class CategoryColor < ActiveRecord::Base
belongs_to :category
end
In the categories table is a list of categories, in category_colors is list of added colors for a category.
I want to display in the collection_select all categories, that have in the table category_colors some colors. How to do that?
So far, I am able to only list all categories in the select tag:
= collection_select(:item, :chosen_category, Category.order('categories.title ASC'), :id, :title, prompt: true)
Thank you very much for an advice
I've achieve that this way:
= collection_select(:item, :chosen_category, #category_colors.map(&:category), :id, :title, prompt: true)
and in the controller for this action:
#category_colors = CategoryColor.group('category_id')
Voila!
Hope this helps
<%= collection_select(:categorycolor, :categoty_id, Category.order('categories.title ASC'), :id, :title, prompt: true) %>

Accessing object in a nested form

i have the following nested form :
<%= form_for #contrat,:url => backend_orders_update_report_url(#contrat) do |f| %>
<%= f.fields_for :contrat_lines do |fcl| %>
<%= fcl.object.inspect %>
<% end %>
<% end %>
the output is the following :
nil
In the nested forms i want to display a few elements not as form but as raw text and a few ones as form field. Usually in a form by doing f.object.name, i would access the name and be able to display it as I want. However, here if i do fcl.object, there is only nil. It should display the inspection of a contrat_line object.
Is it possible to access the data in a nested form?
EDIT :
the controller action :
def show_report
#contrat = Contrat.find(params[:id])
end
Here is what models look like with the relation at the beggining :
ContratLine :
class ContratLine < ActiveRecord::Base
include Priceable
belongs_to :contrat
belongs_to :good
#a enlever ici et dans la base
attr_accessible :active_start,:active,:good_id,:pricing,:contrat
validates :active_start, :presence=> true,:if => "active"
validate :active_start_smaller_than_active_stop
validate :active_start_day_cannot_be_greater_than_28
has_one :pricing, :as => :priceable, :dependent => :delete
before_validation :convert_month_year_to_date
after_save :set_user_subscription_date
Contrat :
class Contrat < ActiveRecord::Base
has_many :contrat_lines, :dependent => :delete_all
belongs_to :user
attr_accessible :user_id,:pricing_id,:state,:adresse_id,:adresse,:payment,:adresse_attributes,:automatic,:start_date,:end_date
enum_attr :state, %w(basket waiting_data to_confirm paid) do
labels :basket=>'Panier', :to_confirm=>'Non payƩ',:paid=>'PayƩ'
end
enum_attr :payment, %w(debit_card wire_transfer cheque direct_debit)
belongs_to :adresse
accepts_nested_attributes_for :adresse, :allow_destroy => true
scope :by_state, lambda { |state| where("state = ?",state) }
scope :last_automatic, where("automatic = true").order("invoice_date DESC")
scope :last_with_adresse, where("state != 'basket'").order("invoice_date DESC")
before_validation :set_numbers
You're missing an accepts_nested_attributes_for :contrat_lines as well as :contrat_lines_attributes in attr_accessible

Rails 3 - Fields_for Nested attributes not showing on form

OK this is weird, I have basically the following classes:
class PriceProfile < ActiveRecord::Base
has_many :prices
has_many :price_profile_date_ranges
attr_accessible :name, :price_profile_date_ranges_attributes
accepts_nested_attributes_for :price_profile_date_ranges
}
class PriceProfileDateRange < ActiveRecord::Base
attr_accessible :end_date, :price_profile_id, :start_date, :prices, :prices_attributes
has_many :prices, :dependent=>:destroy
belongs_to :price_profile
accepts_nested_attributes_for :prices
}
class Price < ActiveRecord::Base
attr_accessible :price_profile_date_range_id, :price_profile_id, :product_id, :value
belongs_to :price_profile
belongs_to :price_profile_date_range
belongs_to :product
}
A price profile defines a pricing scheme for a particular product whose price changes over time. The date ranges over which a price is applied is stored in the price_profile_date_range table and finally the prices table holds all the prices. I'm using the following controller & view to create the form here for setting prices while creating a date range. Basically the form has a start and end date fields and a grid i.e it would have a list of texteboxs against all products to enter the price.
This is the view:
.row
.span9
= simple_form_for(#price_profile_date_range, :class=>'well') do |f|
.form-inputs
= f.input :start_date, :required => true, :as => :string, :input_html =>{:class=>'datepicker'}
= f.input :end_date, :required => true, :as => :string, :input_html =>{:class=>'datepicker'}
= f.input :price_profile_id, :as=>:hidden
%table.table.table-bordered.table-condensed.table-striped
%tr
%td
- #products.each do |product|
%td
=product[:name]
%td
- f.fields_for(:prices) do |price_element|
= price_element.input :value, :class=>'span1'
= price_element.input :price_profile_id, :as=>:hidden
= price_element.input :price_profile_date_range_id, :as=>:hidden
= price_element.input :product_id, :as=>:hidden
.form-actions
= f.button :submit
This isnt exactly the final form - the problem is that the f.fields_for line doesn't seem to execute. In the controller I initialise the #price_profile_date_range object with a set of prices. If I do a raise inspect it shows all the price objects even in the view however the fields_for doesn't execute at all. I'm pretty stuck here real badly.
Try changing the - to a = - sounds silly but maybe that's the problem.

rails3 is not adding the 2nd id to my table

the problem I'm having is company_id is not been save to the details table
I know the company_id is there I check it using <%= debug(params[:id])%> on the form before adding all company details information but for some reason is saving everything else but the company_id
##user.rb
has_one :company
##company.rb
belongs_to :user
has_one :detail
##detail.rb
belongs_to :user
##details controller
def new
#detail = Detail.new
user_id = session[:user_id]
company_id = params[:id]
end
def create
#detail = Detail.new(params[:detail])
#detail.user_id = session[:user_id]
#detail.company_id = params[:id]
end
###settings.html.erb
### this is where i make sure that company_id gets pass with the url
link_to 'New Detail', {:controller => 'details', :action =>'new', :id => company.id }, :class => 'plus'
#####routes
resources :details
resources :companies
resources :users
resources :sessions
I know this may not look pretty or proper if you know a better way please let me know...thanks in advance.
I notice something immediately. You may need to fix your associations first. Assuming, a user has one company and a company has one detail.
##user.rb
has_one :company
##company.rb
belongs_to :user
has_one :detail
##detail.rb
belongs_to :user
Should be:
##user.rb
has_one :company
##company.rb
belongs_to :user
has_one :detail
##detail.rb
belongs_to :company
Although, depending on your domain requirements. I would normally have it as: User has_many Companies. And since details is 1:1 with company, I would include all the details inside company.
I didn't realize this until later but I need it pass values to from on the view to the from like so
<% #companies.each do |company| %>
<%= link_to 'New Detail', {:controller =>'details', :action => 'new', :company_id => company.id}, :class => 'plus' %>
<% end %>
and I need it to collect that value on the from...like so
<%= form_for(:detail, :url =>{:action => 'create', :company_id => #company.id}) do |f| %>
...(values)
<% end %>

Show Name instead of ID in a HABTM relationship

Excuse me if I'm being too much of a beginner but none of the other related answers worker.
I want to show the category name that the links belong to instead of the id.
Here's the migration.
class CreateCategoriesLinks < ActiveRecord::Migration
def self.up
create_table :categories_links, :id => false do |t|
t.references :category
t.references :link
end
end
def self.down
drop_table :categories_links
end
end
The categories model
class Category < ActiveRecord::Base
has_and_belongs_to_many :links
end
The links model
class Link < ActiveRecord::Base
has_and_belongs_to_many :categories
end
And here's what's in the links controller under index and show
#categories = Category.find(:all, :order => 'name')
and here's what's in the index right now but, I've tried every permutation of this that I could find.
<%= link.category.name %>
If it put <%= link.category_ids %>, it'll show the ids.
Try:
<% link.categories.each do |cat| %>
<%= cat.name %><br>
<% end %>