Connecting tables to shopping cart
I have three models and three database tables that I want to connect to one cart, I'm new in rails and have some problem to do this.
My initial idea was
Create model called Service as a parent of models Adverts, Package_of_products, and Subscriptions. And then connect it to cart by Line_item
Already know that I am doing something wrong
Each time when trying add one of my services to Line_items I getting message
ActiveRecord::RecordNotFound in LineItemsController#create
Couldn't find Service without an ID
app/controllers/line_items_controller.rb:44:in `create'
Already I have
def create
#cart = current_cart
service = Service.find(params[:service_id])
#line_item = #cart.line_items.build(:service => service)
respond_to do |format|
if #line_item.save
format.html { redirect_to(#line_item.cart, :notice => 'Line item was successfully created.')
end
I have 4 databas and models my Line_items
class LineItem < ActiveRecord::Base
belongs_to :service
belongs_to :cart
end
Cart
class Cart < ActiveRecord::Base
has_many :line_items, :dependent => :destroy
has_many :services,
has_many :adverts, :through => :services
has_many :package_of_products, :through => :services
has_many :subscriptions,:through => :services
Advert
class Advert < ActiveRecord::Base
belongs_to :service
end
Subscriptions
class Subscription < ActiveRecord::Base
belongs_to :service
end
Package_of_products
class PackageOfProduct < ActiveRecord::Base
belongs_to :service
end
ok, first the association name is belongs_to instead of belong_to, so please correct that misprint.
and then i think you need smth like this:
class Cart < ActiveRecord ::Base
has_many :line_items, :dependant => destroy
has_many :ads, :through => :line_items
has_many :products, :through => :line_items
has_many :services, :through => :line_items
end
check the has_many :through association here
Related
I'm confusing about association.
I tried to write code below but rails was returned me "undefined method `subs'".
def show
#product = Product.find(params[:id])
#materials = #product.materials.subs
respond_to do |format|
format.json { render json: [ #product,#materials ]}
end
end
I want Product model relates to Sub model and I get Sub model record.
If someone knows about this problem to solve please tell me.
class Product < ActiveRecord::Base
has_many :product_materials
has_many :materials, :through => :product_materials
end
class ProductMaterial < ActiveRecord::Base
belongs_to :product
belongs_to :material
end
class Material < ActiveRecord::Base
has_many :product_materials
has_many :products, :through => :product_materials
has_many :material_subs
has_many :subs, :through => :material_subs
end
class MaterialSub < ActiveRecord::Base
belongs_to :material
belongs_to :sub
end
class Sub < ActiveRecord::Base
has_many :material_subs
has_many :materials, :through => :material_subs
end
#product.materials is an array and you cannot chain a association on an array
#product = Product.includes(materials: :subs).find(params[:id])
#materials = #product.materials.flat_map(&:subs)
this will loop over the materials and will return subs for each material
My Models:
class Vip < ActiveRecord::Base
belongs_to :organization
has_many :events
has_many :organizations, :through => :events
end
class Organization < ActiveRecord::Base
belongs_to :user
has_many :events
has_many :vips, :through => :events
end
class Event < ActiveRecord::Base
belongs_to :organization
belongs_to :vip
end
My vips Controller:
def create
#organization = Organization.find(params[:organization_id])
#vip = #organization.vips.build(vip_params)
if #vip.save
redirect_to organization_path(#organization)
else
render 'new'
end
end
def vip_params
params.require(:vip).permit(:name, :about, :organization_id)
end
Before I started using the has_many :through associations, the build method would automatically add the foreign key to the new vip. So my vips table would have the organization_id column populated. Since using the has_many associations, the organization_id column is being left NULL on 'vip#create'.
Is there a reason that build wouldn't work the same way anymore with my new associations?
I'm having trouble nesting my objects that have a has_many through relationships via rails.
My models look like this:
class SessionDetail < ActiveRecord::Base
has_many :session_enrollments, dependent: :destroy
has_many :customers, through: :session_enrollments
end
class SessionEnrollment < ActiveRecord::Base
belongs_to :customers //column name is "customers_id"
belongs_to :session_details //column name is "sessiondetails_id"
end
class Customer < ActiveRecord::Base
has_many :session_enrollments
has_many :session_details, through: :session_enrollments
end
I'm trying to nest a json object to return an array of session details, with a sub array of customers and a subarray (one object) of session_enrollments
My controller current looks like this:
def return_trainers_sessions
#trainer_requests = SessionDetail.where(trainers_id: params[:trainers_id], state: "PENDING")
unless (!#trainer_requests.any?)
respond_to do |format|
msg = {:status => "SUCCESS", :messages => "Requests Found", :requests => #trainer_requests.as_json(:includes => {:customers => {:include =>:session_enrollments}})}
format.json { render :json => msg } # don't do msg.to_json
end
I've also tried making a class method, but am only able to get as far as nesting the customers.
I end up returning no customers or session_enrollments, so my json just looks like I never added the includes to the right hand of .as_json
Watch your pluralization.
class SessionDetail < ActiveRecord::Base
has_many :session_enrollments, dependent: :destroy
has_many :customers, through: :session_enrollments
end
# a session enrollment belongs to a single customer, and a single session detail. Similarly
# the foreign key fields should be singular, customer_id, session_detail_id
class SessionEnrollment < ActiveRecord::Base
belongs_to :customer
belongs_to :session_detail
end
class Customer < ActiveRecord::Base
has_many :session_enrollments
has_many :session_details, through: :session_enrollments
end
I have the following models:
product.rb
class Product
has_many :purchases
has_many :line_items
has_many :orders, :through => :order_products
lineitem.rb
class LineItem
belongs_to :product
belongs_to :cart
belongs_to: order
order.rb
class Order
belongs_to :user
belongs_to :product
has_many :purchases
has_many :line_items, :dependent => :destroy
has_many :orders, :through => :order_products
purchase.rb
class Purchase
belongs_to :order
belongs_to :product
updated:
order_product.rb
class OrderProduct < ActiveRecord::Base
belongs_to :order
belongs_to :product
end
order_controller.rb
if #order.save
if #order.purchase
Cart.destroy(session[:cart_id])
session[:cart_id] = nil
The above are my association for the models. However I face problems in displaying the products from a user. When the items are successfully purchased, the line_items are destroyed.
Does anyone know how do I store all the purchased items into purchase or any other better methods for me to display the products bought by a user?
I initially tried to retrieve line_items and it works. However, after the line_items are destroyed, I am not able to retrieve the relevant products.
Appreciate any help here.
You could try making an order_history for each user -
user.rb
def order_history
#set this up according to how your models are related, etc
#with the idea being to call #user.order_history and getting an array of previous orders
end
and then in order_controller.rb
if #order.save
if #order.purchase
#adapt this pseudocode to suit your needs and
#according to how you've defined `#user.order_history
current_user.order_history = current_user.order_history + #order.line_items
Cart.destroy(session[:cart_id])
session[:cart_id] = nil
Essentially, push the line_items elsewhere so you have a record of them before you destroy the cart.
You need to look at http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association association.
User
has_many :orders
has_many :products, through: :orders
Order
has_many :line_items
has_many :products, through: :line_items
In my form for member_profile, I would like to have role checkboxes that are visible for admins. I would like to used some nested form_for, but can't make it work, so I've resorted to manually creating the check_box_tags (see below), and then manually adding them to member_profile.member.
Note that the Member model is Devise, and I don't want to mix those fields in with my MemberProfile data, in case I change auth systems in the future.
class Member < ActiveRecord::Base
has_one :member_profile
has_many :member_roles
has_many :roles, :through => :member_roles
end
class MemberProfile < ActiveRecord::Base
belongs_to :member
has_many :member_roles, :through => :member
#has_many :roles, :through => :member_roles #can't make this work work
end
class Role < ActiveRecord::Base
has_many :member_roles
validates_presence_of :name
end
class MemberRole < ActiveRecord::Base
belongs_to :member
belongs_to :role
end
Form (haml)
= form_section do
- Role.all.each do |x|
=check_box_tag 'member[role_ids][]',
x.id,
begin #resource.member.role_ids.include?(x.id) rescue nil end
=x.name
member_profiles_controller.rb
def update
if #resource.update_attributes params[:member_profile]
#resource.member.role_ids = params[:member][:role_ids]
redirect_to(#resource, :notice => 'Member profile was successfully updated.')
else
render :action => "edit"
end
end
I've decided it only makes sense to do a nested has_many :through on Update, since the join model is what is being 'gone through' to get to the has_many :through model. Before the hmt is created, there is obviously no record in the join model.