在#show中我有这段代码:
def show
respond_to do |format|
format.html { render :show }
format.json { @my_item.to_json }
end
end
private
def set_trip
@my_item = MyModel.find(params[:id])
end
当我请求“/my_models/1.json”时,它会抛出异常:
Showing app/views/my_models/show.json.jbuilder where line #1 raised:
Missing partial my_models/_my_model with {:locale=>[:en], :formats=>[:json], :variants=>[], :handlers=>[:jbuilder]}. Searched in:
* "app/views"
* "/home/fdsafds/.gem/ruby/2.4.2/gems/apitome-0.1.0/app/views"
为什么?我必须有jbuilder吗?为什么不能简单地将对象转换为json?
答案 0 :(得分:1)
您不必使用private static int[] TABLES = new int[] {1, 2, 3, 4, 5, 6, 7};
public static void main(String[] args) {
System.out.println("Welcome to Joel's Restaurant.");
while (true) {
System.out.println("please enter quit to exit. For booking write you name.");
try (Scanner scanner = new Scanner(System.in)) {
final String name = scanner.nextLine();
if ("quit".equals(name.toLowerCase())) {
break;
}
System.out.print("Number of people accompanying you: ");
final int count = scanner.nextInt();
final int randomTable = Double.valueOf(Math.random()).intValue() % 7;
System.out.println("Mr. " + name + ", table no." + TABLES[randomTable] + " is assigned to you with count: " + count + ".");
System.out.println();
}
}
}
。
您需要在json格式块中调用jbuilder
。请参阅渲染json上的documentation。
2.2.8渲染JSON
JSON是许多Ajax库使用的JavaScript数据格式。轨道 内置支持将对象转换为JSON并进行渲染 JSON回到浏览器:render json:@product
您不需要在要渲染的对象上调用to_json。 如果使用:json选项,render将自动调用to_json 对你而言。