开发者

collection_select values and names

I'm having a hard time wrapping my head around a collection_select that I'm trying to do. Some background: I have a nested model where I have an layout and each layout can have a set number of images. As part of the input, the user is allowed to decide what image goes in what order. This is dictated by the layout_placement value of the image. This currently works, the layout_placement is a plain text field where the use开发者_如何学Pythonr can input etc.

<%= f.fields_for :images do |builder| %>
  <%= builder.file_field :image %> 
  <%= builder.label :layout_placement %> <%= builder.text_field :layout_placement, :size => 3%>
  <br /><br />
<% end %>

What I need though is a drop-down in place of the plain text field that will allow me to limit the value of the layout_placement selected - this is based on the number of spaces available (each layout is different and has anywhere from 2 to 5 image slots).

I already have a field in the layout called image_slots that gives me the number of available image slots for the layout being used. So I want to make my available options a range from 1 to the number of image slots. I'm trying to do something like this:

<%= builder.collection_select :layout_placement, 1..@layout.image_slots, ???, ??? %>

And I get stuck on what to pass for the :id and :name methods. I've tried going simpler and just using the select_tag but I get stumped in a different area in that, since it's a nested model the :object#method settings goes wrong.

Any help in making either option work would be greatly appreciated.


In your case you don't really need to use the collection_select since you want the text and value of your options to be the same thing (ie: 1..@layout.image_slots). Try this

<%= builder.select :layout_placement, 1..@layout.image_slots %>

In the case where your image_slots might return nil just make sure you handle it properly

<%= builder.select :layout_placement, 1..(@layout.image_slots || 1) %>

To validate the placement values are uniq, add this to your Image model

validates_uniqueness_of :layout_placement, :scope => :layout_id
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜