我有一个食谱,其中包含recipe_ingredients和has_many成分通过recipe_ingredients。我正在尝试编辑配方控制器中recipe_ingredients表的记录。现在使用我的表单,它列出了所有要编辑的字段(我只想要一个)。另一件事是它根本没有更新记录。提前感谢你能解决这个问题。这是编辑表格。
<%= form_for @recipe, remote: true do |recipe_form| %>
<%= recipe_form.fields_for :recipe_ingredients do |f| %>
<%= f.label :amount %>
<%= f.number_field :amount, step: :any %>
<%= f.submit %>
<% end %>
<% end %>
和控制器。
def edit
@recipe = Recipe.find(params[:id])
@recipe_ingredients = @recipe.recipe_ingredient
end
def update
@recipe = Recipe.find(params[:id])
@recipe.recipe_ingredients = RecipeIngredient.where(recipe_id: params[:id])
end
private
def recipe_params
params.require(:recipe).permit(:name, :recipe_ingredient_ids => [], :ingredient_ids => [])
end
答案 0 :(得分:0)
没有最好的方法,但我将:recipe_ingredients
添加到路线,并将编辑和创建移动到ingredients_controller
和添加了这个超级丑陋的path_helper,大声笑。
resources :users, only: [:new, :create, :show ]
resources :recipes, :recipe_ingredients do
resources :ingredients, only: [:new, :create, :edit, :update]
end
<tbody>
<% @recipe.recipe_ingredients.each do |recipe_ingredient| %>
<tr>
<td><%#= check_box_tag "recipe_ingredient_ids[]", recipe_ingredient.id %> </td>
<td><%= recipe_ingredient.ing_name %></td>
<td><%= recipe_ingredient.amount %> <%= link_to 'Edit Ingredient',
edit_recipe_ingredient_ingredient_path(recipe_ingredient) %> </td>
</tr>
<% end %>
</tbody>
</table>
更新后的更新操作
def update
@recipe = Recipe.find(params[:id])
recipe_ingredient = RecipeIngredient.find(params[:recipe_id])
recipe_ingredient.update(amount: params[:recipe_ingredient][:recipe_ingredients][:amount].to_f)
# require "pry"; binding.pry
redirect_to recipe_path(@recipe)
end
我确信有更好的方法可以做到这一点,我很好吃,哈哈。