开发者

Rails: embedding and retrieving array from form

I'm getting tripped up in Ruby, Rails & HTML syntax. Hoping some Rails ninja can help me with what's likely a trivial problem....

Post has_many Photos

Photo has a string :image attribute

In Post's _form.html.haml I would like to embed (in a hidden_field) the contents of the image attribute for each Photo associated with a Post...and then get it back out when form is submitted. I could do this either by A) adding one hidden_field for each photo.image or B) create a single array containing all associated photo.images.

I'm tripped up by how best to embed this...(A) or (B) neither of which I've fully perfected.

# _form.html.haml:
  = form_for @post do |f|

    - if @post.photos.any?
      - @post.photos.each do |photo|        -# (A)
        = f.hidden_field :image_cache       -# (A)
      = f.hidden_field :images_cache        -# (B)
    = f.file_field :photos, :multiple => true

  .actions
    = f.submit 'Save'


#post.rb  (A)
  def image_cache
    self.photos.any? ? photos.first.image : nil   -# works with `first` 
                                                  -# but not sure how to 
                                                  -# pass id of others?!?
  end


#post.rb:  (B)开发者_JS百科
  def images_cache
    photos.map { |i| i.image }
  end

Problem with (A) is I don't know how to pass the photo back to the Post model to return the image_cache attribute off of it?!? f.hidden_field :image_cache(photo) doesn't work

Problem with (B) is the images_cache returned by the Post model is an array but once embedded in the HTML page and returned by the following post request it has become a string representation of an array: [/uploads/tmp/20110729-1216-15902-2013/Before_Green_Flash.JPG, /uploads/tmp/20110729-1216-15902-5934/Before_Green_Flash2.JPG] and therefore does not respond to each.

Any help with either or both situations would be greatly appreciated!


For approach a, why not: = f.hidden_field photo.image

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜