Populating a Select with Model Data in Rails

前端 未结 2 1120
执念已碎
执念已碎 2021-02-07 22:08

I feel the need to apologize for asking such a simplistic question, but I\'m getting increasingly frustrated with the Rails Guides. I\'m sure they answer my question, but they d

相关标签:
2条回答
  • 2021-02-07 22:27

    Well, I'm not sure it's the best way, the Rails way or, frankly, even an elegant way, but here's the code I've used that seems to be working so far.

    <%= f.label 'Albums' -%>
    <%= collection_select( :image, :album_ids, current_user.albums, :id, :name, {}, { :multiple => true } ) -%>
    

    At this point, when I say "working", all I can really attest to is that the page renders with no errors and the appropriate album or albums are selected when I edit an image. I'm still shocked at how difficult it was to cobble together a "full" solution from a lot of disparate sources.

    0 讨论(0)
  • 2021-02-07 22:34

    I think that select elements are one of the more confusing aspects of Rails, because as you said there seem to be a number of ways to do it.

    Try this:

    <%= f.select(:album_id, @image.albums.all.collect {|a| [a.name, a.id]}) -%>
    
    0 讨论(0)
提交回复
热议问题