SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Zealot matches's Avatar
    Join Date
    Aug 2006
    Posts
    196
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    It works, I just want to understand why

    Hello,

    I am still pretty new with rails. I am currently modifying DHH's create a blog screencast. I wanted to add a select dropdown choice for a topic on my new blog form. I created a new topics table a one to many relationship with the posts table. I had a little trouble getting the select show the contents of the topics table but with a little help and a lot of trial and error it works now. I just want to see if someone wouldn't mind explaining or at least pointing me to an appropriate article on an explanation on why the code below works.

    <%= select "post", "topics_id", @topics.map { |t| [t.topic,t.id] }, { :include_blank => true } %>

    I will tell you what I (think I) know:

    I am creating a select element based on the post's topic_id.

    @topics.map then I guess provides the information to fill the select.

    then I don't know what |t| means or why it precedes topic and id

    and include blank just means by default nothing will be selected.

    Please tell me what I have right, wrong and what I need to know.


    Thanks for looking

  2. #2
    SitePoint Guru
    Join Date
    Aug 2005
    Posts
    986
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    <&#37;= select
    Call the select() helper.

    Code:
    "post", "topics_id",
    The name of the <select> tag will be post[topics_id]

    Code:
    @topics.map { |t| [t.topic,t.id] },
    Populate the select tag with <option> tags. The text of the option will be t.topic, and the value will be t.id.

    Like this:

    Code:
    <select name="post[topics_id]">
    <% for t in @topics %>
      <option value="<%= t.id %>"><%= t.topic %></option>
    <% end %>
    </select>
    Google "ruby map" and "ruby blocks" for information about the strange notation.

    Code:
     { :include_blank => true } %>
    Include an empty <option></option>.

    BTW, here's a more modern way:

    Code ruby:
    <% form_for :post, ... do |f| %>
      ...
      <%= f.collection_select "topic_id", @topics, "id", "topic" %>
      ...
    <% end %>

  3. #3
    SitePoint Zealot matches's Avatar
    Join Date
    Aug 2006
    Posts
    196
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    awesome thanks!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •