I am using Rails as a JSON API. My database has the following structure: the City model has_many Users, which in turn has_many Businesses.
When I send a GET request to businesses#index, I want Rails to return all the businesses in a given city, not just for a given user. What's the best way to do this?
I've already tried the given code below as a first pass, which is returning an internal server error (500).
def index
@city = City.find(params[:city_id])
@users = @city.users
@businesses = @users.businesses
render json: @businesses
end
Can you try this? Because of the @user
is an array. so the error will occuring.
# city.rb class City < ApplicationRecord has_many :users end #user.rb class User < ApplicationRecord belongs_to :invoice has_many :businesses end #business.rb class Business < ApplicationRecord belongs_to :user end # your controller def get_business @city = City.find(params[:id]) @business = @city.users.includes(:business) render json: @business end
Add a new relationship to your City model: has_many businesses, through: users
Then when you have a specific city you can get all businesses: @city.businesses
You might also want to try starting with the Business model to make the query.
Business.joins(user: :city).where(cities: { id: params[:city_id] })
joins
uses the association names
where
uses the table names
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.