¿No se establece el valor predeterminado de los rieles para seleccionar?

I have a Comment and a Post, where the Post has_many Comments and the Comment belong_to the Post.

In the admin interface, I have a dropdown menu for selecting which post a comment belongs to.

Aquí está el código:

<%= form_for @comment do |f| %>
<p>
    <%= f.label :text, "Comment Text" %><br />
    <%= f.text_field :text %>
</p>

<p>
    <%= f.label "Post" %><br />
    <%= f.select(:post_id, options_from_collection_for_select(Post.all, :id, :title), :include_blank => true) %>
</p>

<p>
    <%= f.submit "Update" %>
</p>

However, the select tag default value is not being selected, even though it says in the documentation it should automatically default to @comment.post_id. Any ideas why this isn't happening?

preguntado el 08 de noviembre de 11 a las 19:11

debería ser belongs_to. ¿Es un error tipográfico? -

What's the emitted HTML? -

1 Respuestas

Rails will only automatically use @comment.post_id if you just pass an Array as the second object instead of using options_from_collection_for_select. Aquí esta la documentación relevante. So if you did this, it would work fine:

<%= f.select(:post_id, 
             Post.all.collect {|p| [p.title, p.id] }, 
             :include_blank => true) %>

Si quieres quedarte con options_from_collection_for_select, then you need to tell it what value to use as the selected value:

<%= f.select(:post_id, 
             options_from_collection_for_select(Post.all, :id, :title, @comment.post_id), 
             :include_blank => true) %>

respondido 09 nov., 11:00

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.