Has_many <-> belongs_to trouble

Hi all, finally im starting with rails, i have a simple relationship
has_many ans belongs_to that i dont now how to manage the update action,
here are my models

class Item < ActiveRecord::Base
has_many :images
end

class Image < ActiveRecord::Base
belongs_to :item
end

And my table structure:

Items => id, title, desc
Images => id, image, item_id

ok, i have a number of items and each item has an image assigned, i can
display the item info and its assigned image with

<% for image in @item.images %>
<%= image_tag("/images/publicas/" + image.image) %>
<% end %>

thats not a problem, the problem comes when i want to update the item, i
cant find a way to update its image too, im trying to fill a combobox(in
fact to fill the combo there´s no problem) in the edit.rhtml view so i
can choose wich image assign to the item and when i click the edit
button it be saved on the controller but i cant figure it out how pass
the image/id parameters.

Hope you can help me with this, Please be gentle im still learning :frowning:

Anyone? i have really tried to achieve this but i just cant figure it
out how to make it work.

Hi Nhila,

I am also learning Rails and are trying to do similar things as you (if
I understand your situation correctly.) What I did is store the
parameters I needed in session like

session[:image_id]

If you find a better way, please let me know :slight_smile:

Victor

I should really read what I write before sending:
“now, in you view, you have params[:image] which contains a hash
like…”: of
course, it’s not in your view, but in in your controller.

Okay, so if I get it right, you have items, each of them having many
images.

Now, you simply want to associate the images to each item. You can use
different controls for that, including the combo box, which I will
briefy
describe.

You view could look like that (that’s an image you are editing, and you
will
choose which item it belongs to. Editing an item would rather require a
“check box control”):

<%= @items= Item.find(:all)
collection_select(:image, :item_id, @items, :id, :item)
%>

now, in you view, you have params[:image] which contains a hash like:
“image”=>{“name”=>“my image name”, “item_id”=>“12”}
if you have setup your form as usual, you should also have params[:id] =
id
of your image

Therefore, in you controller, you can update like:
image = Image.find(params[:id])
if image.update_attributes(params[:image])
redirect in case of success
else
render form in case of failure
end

Hope this helps.

Regards,

Nicolas

That should create a combo box where the names of the