I am fairly new to rails and currently working on the functionality of my personal project where I have multiple models. I have these models - Places, Favorites, ThingsToDo, User.
User, ThingsToDo, and Favorites have a many-many relationship where Favorites is a join table. /places (PlacesController) renders all the places as of now. I am trying to render cities that have the most favorites across all their things_to_do should be shown first followed by the next places that are not added by as favorites in user's account.
Note(places and things_to_do have has_many associations).
Favorite Model - group_by_favorite(method name)
class Favorite < ApplicationRecord
belongs_to :user
belongs_to :things_to_do
end
#validates :things_to_do_id, uniqueness: { scope: :user_id, :message => "has already been added as favorite" }
def group_by_favorite
Favorite.joins(:things_to_do,:user).group(:place_id).count
end
Place Model
has_many :things_to_dos
end
def self.top_places
@places_render = group_by_favorite.sort
end
Place Controller
class PlacesController < ApplicationController
def index
@places_render = top_places()
places = Place.all
render json: places
end
When I am trying to run /places route, I am getting this error
"#<NoMethodError: undefined method `top_places' for #<PlacesController:0x00000000011aa8>>",
My React Code for /places
export default function DestinationContainer({user}){
const[allDestination,setAllDestination]= useState([])
const [search, setSearch] = useState("");
useEffect(()=> {
fetch("/places")
.then((res) => res.json())
.then((data) => {
setAllDestination(data)
})
},[])
const filterPlaces = allDestination.filter(
(destinations) =>
destinations.city.toLowerCase().includes(search.toLowerCase()) )
return (
<>
<Switch>
<Route exact path= "/places">
<SearchPlace search={search} setSearch={setSearch}/>
<DestinationView allDestination= {filterPlaces} user = {user} />
</Route>
<Route path="/places/:destinations" >
<ThingsToDoRender user ={user} />
</Route>
</Switch>
</>
)
}
Is there a way that I can fix this error?I also tried to use scope but not sure if it is applicable in this case.
CodePudding user response:
As your error says, the method top_places()
is not defined in your PlacesController
class. But it is a Place
class function. So try the following:
@places_render = Place.top_places()