Karlis
Karlis

Reputation: 1501

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

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

Upvotes: 4

Views: 3406

Answers (1)

sathyajith
sathyajith

Reputation: 46

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.

Upvotes: 2

Related Questions