我想从控制器中的方法调用JavaScript函数,函数写入文件名为create.js.erb的文件但错误ActionController :: UnknownFormat 我不知道是什么问题?
应用程序/视图/ favorite_places / create.js.erb
function my_function()
{
swal("Place is not saved in google maps!", "Please move the marker to the desired location and add its name");
}
应用程序/控制器/ favorite_places_controler
def create
#Checks if the current user have this favorite place already ,it renders Favorite Place already exists
if current_user.favorite_places.include?(FavoritePlace.find_by(:name => favorite_place_params[:name]))
id=FavoritePlace.find_by(:name => favorite_place_params[:name]).id
redirect_to favorite_places_path , notice: 'Favorite place already exists'
else
#Checks if the favorite Place exists in the database it finds the place puts it in the variable favorite place
if FavoritePlace.exists?(:name => favorite_place_params[:name])
@favorite_place = FavoritePlace.find_by(:name => favorite_place_params[:name])
#Or it will create a new one with the allowed parameters only.
else
@favorite_place = FavoritePlace.new(favorite_place_params)
@favorite_place.save
end
id=@favorite_place.id
#It assigns the favorite place to the user.
UserFavoritePlace.add_favorite_place(current_user,@favorite_place)
redirect_to favorite_places_path , notice: 'Favorite place was successfully added.'
respond_to do |format|
format.js { render :js => "my_function();" }
end
end
end
答案 0 :(得分:0)
在respond_to块之前有一个redirect_to,这是错误的 - redirect_to应该在respond_to块内的format.html块中。
您的未知格式错误可能是由于控制器试图处理和html请求引起的,您不会在respond_to块内处理。尝试更改此
redirect_to favorite_places_path , notice: 'Favorite place was successfully added.'
respond_to do |format|
format.js { render :js => "my_function();" }
end
到这个
respond_to do |format|
format.html { redirect_to favorite_places_path , notice: 'Favorite place was successfully added.' }
format.js { render :js => "my_function();" }
end