I am working on a travel planning web app project in Rails and Ract. In my Ruby on Rails backend I have a model Place that belongs to my model Trip. in React.js on the frontend I am trying to render just those places that belong to a certain trip in a Modal. At present, I am rendering all the places in my database (because on my backend the index method in calling Place.all) so when I open my Modal for a certain trip, it displays all of the places rather than just the places that belong to that trip.
I need a way on either the back or front end to render only those places that belong to the trip that I am opening in the Modal
Currently my code looks like this:
Rails backend:
def index @places = Place.all render json: @places.as_json end
React frontend Home.jsx
//Places actions
const [places, setPlaces] = useState([]);
const handleIndexPlaces = () => {
axios.get("http://localhost:3000/places.json").then((response) => {
console.log(response.data);
setPlaces(response.data);
});
};
useEffect(handleIndexPlaces, []);
//returning
<Modal show={isTripShowVisable} onClose={handleHideTrip}>
<TripsShow places={places} trips={trips} />
</Modal>
//tripsShow
export function TripsShow(props) {
return (
<>
<h2>Places to visit on this trip:</h2>
<div>
{props.places.map((place) => {
return (
<div key={place.id}>
<h3>{place.name}</h3>
</div>
);
})}
</div>
</>
);
}
I have tried changing the backend to Place.where(trip_id: current_trip.id) but I know that I don't currently have a current_trip so that doesn't work.
You can pass the trip ID as a parameter in the axios GET request to the backend, and then retrieve only the places that belong to the trip with the same ID in the controller.
Backend:
Frontend:
The
TripsShowtakes more props now, it needs the selected trip, and a function to resolve the places for it :