I'm new to Ruby on Rails and don't understand private methods using strong params.
How would I refactor this? Can someone give me an example?
I've tried looking it up, but all I find are examples of CRUD using strong params in CRUD.
def create
title = params["song"]["title"]
rating = params["song"]["rating"]
artist_id = params["song"]["artist_id"]
song = Song.create(title: title, rating: rating, artist_id:
artist_id)
redirect_to song_path(song)
end
def update
title = params["song"]["title"]
rating = params["song"]["rating"]
artist_id = params["song"]["artist_id"]
song = Song.find(params[:id])
song.update(title: title, rating: rating, artist_id: artist_id)
redirect_to song_path(song)
end
Have you tried anything like this? Note that you're not managing errors here
def create
song = Song.create(song_params)
redirect_to song_path(song)
end
def update
song = Song.find(params[:id])
song.update(song_params)
redirect_to song_path(song)
end
private
def song_params
params.require(:song).permit(:title, :rating, :artist_id)
end
In this line you're simply whitelisting those three params' names in a song object and this method is called in the create
and update
actions
params.require(:song).permit(:title, :rating, :artist_id)
This means that if a duration
was sent inside the song object that attribute is not changed because it's not whitelisted
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.