Richlewis Richlewis - 4 years ago 100
Ruby Question

find(params[:id]) and instance variable returns <Object>

Hopefully an answer to this question will clear up my understanding a little of what is going on here

Within my Images Controller I have a

show
action

class ImagesController < ApplicationController
def show
@image = Image.find(params[:id])
end
end


When I am on a page
/images/6
the
params[:id]
is 6

Routes

resources :images, only: [:show]


So on this page I have a form_for to write to a different model, within a hidden field (for now) I have

<%= form_for(@cart_item, url: cart_item_path, :remote => true do |f| %>
<%= f.hidden_field :image_id, value: @image %>
<% end %>


Now I would expect the value to equal 6, but when i inspect it the value is
#<Image:0x007fe41413b528>
, thus when submitting the form saves the image_id as 0.

And i also realise that if i put @image.id i would get the id, but that's not the way I thought it worked

As stupid as it may sound what am i missing?

Any help appreciated

Thanks

Answer Source

You should be doing it like @image.id

<%= f.hidden_field :image_id, value: @image.id %>

@image holds the record, not id

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download