John
John

Reputation: 5905

Passing an object through a link_to command to be referenced in the model#new page

I'm creating a basic loyalty card application, with model Merchant and Loyaltycard. In the merchant#show view I have this line

<%=link_to 'New Loyalty card', new_loyaltycard_path(:merchant_id=>1) %>

I'm trying to pass the merchant ID to the loyaltycard#new view so it will be automatically selected as the merchant for that card. In loyaltycard#_form (which gets called by loyaltycard#new) I have the lines

  <%if @merchant%>
  <%= f.hidden_field :merchant_id, :value => @merchant.id %>
  <%else%>
   <div class="field">
    <%= f.label :merchant_id %><br />
    <%= f.text_field :merchant_id %>
  </div>
  <%end%>

But I keep getting and error that says can't call id for class Nil. Is there a better way of doing this?

Here is the controller code for loyaltycard

  def new
    @loyaltycard = Loyaltycard.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @loyaltycard }
    end
  end

  # GET /loyaltycards/1/edit
  def edit
    @loyaltycard = Loyaltycard.find(params[:id])
  end

  # POST /loyaltycards
  # POST /loyaltycards.json
  def create
    @loyaltycard = Loyaltycard.new(params[:loyaltycard])

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

The error is

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

Upvotes: 0

Views: 1693

Answers (2)

TheDelChop
TheDelChop

Reputation: 7998

What you need to do in your new action is using the params[:merchant_id] to look up and set @merchant

@merchant = Merchant.find(params[:merchant_id])

Then your code should work, without that, @merchant is nil, and you can't call the method :id on nil

Upvotes: 1

zkMarek
zkMarek

Reputation: 5504

You're not setting variable @merchant anywhere in your controller, but you use it the view.

Upvotes: 0

Related Questions