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
Related
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 have a comments model which is a polymorphic association which is involved with Statuses and Photos. How can I create this polymorphic association to also belong to a User so that when a user creates a comment under statuses or photos it will also recieve the current_user id?
this is what I have as of now-
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
belongs_to :user
end
class User < ActiveRecord::Base
has_many :comments
end
class Status < ActiveRecord::Base
has_many :comments, as: :commentable
end
class Photo < ActiveRecord::Base
has_many :comments, as: :commentable
end
just to reiterate, how can I create a comment as a user but also have it under status or photo? it would need the user_id.
This is where I am having the trouble-
how should I set this up?
def create
#comment = #commentable.comments.new(comments_params)
if #comment.save
redirect_to #commentable, notice: "Comment created"
else
render :new
end
end
Try this
class Comment < ActiveRecord::Base
belongs_to :likable, :polymorphic => true
belongs_to :commentable, :polymorphic => true
belongs_to: user
class User < ActiveRecord::Base
has_many :statuses, :as => :likable
has_many :photos, :as => :commentable
has_many :comments
class Status < ActiveRecord::Base
has_many :comments, :as => :likable, :dependent => :destroy
class Photos < ActiveRecord::Base
has_many :comments, :as => :commentable, :dependent => :destroy
It's a little bit hacky but I found a workaround. So in my CommentsController i did this:
def create
new_params = comments_params
new_params[:user_id] = current_user.id
#comment = #commentable.comments.build(new_params)
if #comment.save
redirect_to #commentable, notice: "Comment created"
else
render :new
end
end
that placed the user_id which is what I needed.
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
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
im working on this model association class assignment. the basic association works, but im having issue with the "category"-page view.
Category Page Output should be (/categories/1)
Dish-ID
Dish-Title
Restaurant-Title <= HOW DO I GET THIS VALUE?
rules:
- dish belongs to one category
- same dish can be in multiple restaurants
class Category < ActiveRecord::Base
has_many :dishes
end
class Dish < ActiveRecord::Base
belongs_to :category
end
class Restaurant < ActiveRecord::Base
has_and_belongs_to_many :dishes
end
class DishRestaurant < ActiveRecord::Base
has_many :restaurants
has_many :dishes
end
Category Controller
def show
#category = Category.find(params[:id])
#dishes = #category.dishes
// RESTAURANT TITLE ??
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #category }
end
Category View:
<%= debug #dishes %>
any hint would be helpful.
thanks
pete
Define you models properly:
class Dish < ActiveRecord::Base
belongs_to :category
has_and_belongs_to_many :restaurants
end
class Restaurant < ActiveRecord::Base
has_and_belongs_to_many :dishes
end
This would use the implicit join table names "dishes_restaurants". You only need a join model is you store some join specific information, like price of the dish in the restaurant. In which case you models should be like:
class Dish < ActiveRecord::Base
belongs_to :category
has_many :dish_restaurants
has_many :restaurants, through => :dish_restaurants
end
class Restaurant < ActiveRecord::Base
has_many :dish_restaurants
has_many :dishes, through => :dish_restaurants
end
class DishRestaurant < ActiveRecord::Base
belongs_to :restaurant
belongs_to :dish
end
Whatever approach you follow, you can do dish.restaurants to retrieve the list of the restaurants which serve the dish.