被称为nil的id,它会错误地为4 - 如果你真的想要id为nil,请使用object_id

时间:2012-04-18 12:00:40

标签: ruby-on-rails-3

我想知道是否有人可以帮助我。我现在正在学习ROR并遇到了一些麻烦。 我已经创建了other_users并使用scaffold发布了模型。 other_users有很多:帖子等等。 我们的想法是,当用户登录并创建帖子时,show action会显示创建此帖子的用户的名称。  我想知道是否有人可以通过电话给我。

发布控制器

def new
    @post = Post.new(:other_user_id => @other_user.id)

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @post }
    end
  end
def create
    @post = Post.new(params[:post])

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render json: @post, status: :created, location: @post }
      else
        format.html { render action: "new" }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

发布视图_form:

<%= form_for(:post, :url => {:action => 'create', :other_user_id => @other_user.id}) do |f| %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %><br />
    <%= f.text_area :content %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

我知道这有点不对劲,但我对此很新,所以我无法自己解决这个问题

1 个答案:

答案 0 :(得分:2)

第2行@other_user未知,所以它是零。我们试图从一个nil获取id,因此它会产生一个名为called id for nil的错误。初始化@other_user并重试。