[英]How to use call method from Model to controller in Rails
我是 Rails 的新手,目前正在處理我擁有多個模型的個人項目的功能。 我有這些模型——Places、Favorites、ThingsToDo、User。
User、ThingsToDo 和 Favorites 具有多對多關系,其中 Favorites 是一個連接表。 /places (PlacesController) 現在渲染所有的地方。 我正在嘗試呈現在所有 things_to_do 中擁有最多收藏夾的城市應該首先顯示,然后是用戶帳戶中未添加為收藏夾的下一個地方。
注意(places 和 things_to_do 有 has_many 關聯)。
最喜歡的 Model - group_by_favorite(方法名)
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
地點 Model
has_many :things_to_dos
end
def self.top_places
@places_render = group_by_favorite.sort
end
地點 Controller
class PlacesController < ApplicationController
def index
@places_render = top_places()
places = Place.all
render json: places
end
當我嘗試運行 /places 路線時,出現此錯誤
"#<NoMethodError: undefined method `top_places' for #<PlacesController:0x00000000011aa8>>",
/places 我的 React 代碼
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>
</>
)
}
有什么方法可以修復這個錯誤嗎?我也嘗試使用 scope 但不確定它是否適用於這種情況。
正如您的錯誤所說,方法top_places()
未在您的PlacesController
class 中定義。但它是一個Place
class function。因此請嘗試以下操作:
@places_render = Place.top_places()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.