在rails上呈现部分时未定义的变量错误

时间:2016-02-26 21:41:01

标签: ruby-on-rails render partial

我正在尝试将渲染代码放入edit.html.erb并创建_form.html.erb。 我有这些代码用于edit.html.erb

    <h1>Main#edit</h1>
    <h1>Editing zone</h1>
    <%= render partial: "form", locals: {addresses: @addresses} %>

和_form.html.erb的这些代码

    <%= form_for(addresses)do |f| %>
  <p>
  <b>name</b><br>
  <%= f.text_field :address %>
  </p>
  <p>
  <%= f.submit %>
  </p>
  <% end %>

和地址是一组地址。

我有这个错误:       无法找到带有&#39; id&#39; =的地址       提取的来源(第21行):

  def edit
 @address = Address.find(params[:id])  this is 21th line
  if request.post?
  if (@address.update_attributes(address_params))
  redirect_to :action=>"index"

请您帮忙检查我的代码中有什么问题吗?

这是我的控制器的代码:

    class MainController < ApplicationController
    def index
    @addresses = Address.all
    end

    def new

    end

    def add
    address = Address.new(address_params)
    if (address.save)
    redirect_to :action=>"index"
    else
     flash[:notice]="Error saving, try again"
     redirect_to :action=>"index"
     end
    end

    def edit
    @address = Address.find(params[:id])
    if request.post?
    if (@address.update_attributes(address_params))
    redirect_to :action=>"index"
    else
    render :action=>"edit"
        end
      end
    end

    def delete
    address = Address.find(params[:id])
    address.destroy
    redirect_to :action=>"index"
    end

    private
    def address_params
    params.require(:address).permit(:name,:address,:email,:phone)
    end
    end

这是我的模特: my data structure

1 个答案:

答案 0 :(得分:0)

我需要查看更多的控制器代码,但看起来Rails正试图在params内找到与id匹配的地址:

 def edit
   @address = Address.find(params[:id])

您似乎有一个路由设置来处理此编辑操作:

get 'resource/:id', to: 'ResourceController#edit'

当您尝试在浏览器中访问'/ resource / 1'(或任何您的网址)时,它应该找到该地址(假设您的数据库中存在id = 1的地址)