我是ruby的新手,但好像我有一些东西,我应该能够循环或by defining a :collection
渲染它们。
在这里,每个花园可能分配了许多植物。我有一个部分,用植物卡和#34;布局。这个视图正确地为每个花园渲染植物:
视图/花园/ show.html.haml
.row.plant-cards
- @garden.plants.each do |plant|
= render("shared/plants/card", {plant: plant, garden: @garden} )
视图/共享/植物/ _card.html.haml
.col-md-2
.plant.thumbnail.text-center
= button_to("+", add_to_garden_path(plant, @garden.id), {method: :post ,remote: true})
= link_to(plant) do
= image_tag("http://lorempixel.com/g/150/150/food/",:alt => plant.name)
%h4.plant__title.caption= plant.name
我正在尝试通过ajax更新花园页面上的渲染植物。似乎我需要坚持渲染植物的输出" card"在.html()
函数中使用.each()
似乎很笨拙。看起来我应该能够将植物设置为:collection
,就像我在下面尝试做的那样,但这不起作用:
视图/植物/ add_to_garden.js.erb (抱歉混合haml / erb - 我也在探索它)
<% flash.each do |key, message| %>
$("#flash").html("<%= j render partial: "shared/flash_message", locals: {key: key, message: message } %>");
<% end %>
$(".plant-cards").html("<%= j render :partial => 'shared/plants/card', :collection => @garden.plants, :locals => {garden: @garden} %>");
当我对我的应用程序进行ajax调用时,我得到了这个运行时错误:
Started POST "/plants/2/add_to_garden/1" for ::1 at 2016-12-30 20:32:18 -0500
Processing by PlantsController#add_to_garden as JS
Parameters: {"authenticity_token"=>"qJU/CEZudZFP9l6r1qdAlXJQrfY7fB0aZHmjRJh2yQO0IzxilP47mP2UjDDAmBNJouFtoAWkv/hJ2gCNR5BpgQ==", "id"=>"2", "garden_id"=>"1"}
Garden Load (0.3ms) SELECT `gardens`.* FROM `gardens` WHERE `gardens`.`id` = 1 LIMIT 1
Plant Load (0.2ms) SELECT `plants`.* FROM `plants` WHERE `plants`.`id` = 2 LIMIT 1
(0.1ms) BEGIN
SQL (0.2ms) INSERT INTO `gardens_plants` (`garden_id`, `plant_id`) VALUES (1, 2)
(160.8ms) COMMIT
(0.2ms) BEGIN
User Load (0.3ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
(0.1ms) COMMIT
Rendered shared/_flash_message.html.erb (0.3ms)
Plant Load (0.5ms) SELECT `plants`.* FROM `plants` INNER JOIN `gardens_plants` ON `plants`.`id` = `gardens_plants`.`plant_id` WHERE `gardens_plants`.`garden_id` = 1
Rendered shared/plants/_card.html.haml (29.7ms)
Rendered plants/add_to_garden.js.erb (42.3ms)
Completed 500 Internal Server Error in 238ms (ActiveRecord: 162.9ms)
NameError - undefined local variable or method `plant' for #<#<Class:0x007fdf9be0f6c8>:0x007fdf9bce6350>:
app/views/shared/plants/_card.html.haml:3:in `_app_views_shared_plants__card_html_haml___4163891484537289381_70299132319600'
...
答案 0 :(得分:0)
只是将@ Deep的答案放入一个问题,他建议
尝试使用如下:
<%= j render partial: 'shared/plants/card', collection: @garden.plants, as: :plant, locals: { garden: @garden } %>
将@ garden.plants集合指定为:plant
就可以了。