Called id for nil, which would mistakenly be 4 — if you really wanted the id of nil, use object_id

北城余情 提交于 2019-12-23 13:25:14

问题


I would like to know if someone could help me. I'm learning now ROR and have run in some troubles. I have created other_users and post model using scaffold. other_users has many:posts and so one. The idea is that, when the user is logged in and creates a Post, in show action shows the name of the user which created this post. I would like to know if someone can tel me with this.

Post controller

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

Post view _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 %>

I know that something is wrong with that, but i'm quite new with that so i can't figure it out on my own


回答1:


At line 2 @other_user is not known so it is nil. We are trying to get the id from a nil so it yields error called called id for nil. Initialize @other_user and try again.



来源:https://stackoverflow.com/questions/10208927/called-id-for-nil-which-would-mistakenly-be-4-if-you-really-wanted-the-id-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!