How do I get Rails select() to work?
I'm running Rails 2.3.5 on a hosted server, and cannot upgrade to 3.
I have one database, and it has a list of cartoons with id
, date
, and title
. I can navigate through them using text links, and I also want to be able to navigate using a dropdown select
, but I can't get the select
tag working. This isn't a form to create a new element. Whereas the form
shows up (being empty), the select
tag does not show up, not even an empty select
tag.
Here's what I have:
*comics_controller.rb*
class ComicsController < ApplicationController
before_filter :get_all_comics
def get_all_comics
@comics=Comic.find(:all, :order => "date DESC")
end
def view
if params[:id].nil?
@comic=@comics.first
@prev=@comics[1]
else
@comic=Comic.find(params[:id])
@prev=Comic.find(:first, :conditions => ["date < ?", @comic.date],
:order => "date DESC")
@next=Comic.find(:first, :conditions => ["date > ?", @comic.date],
:order => "date ASC")
end
end
end
comics/view.html.erb
<% form_for :comics, :url => { :action => "view" } do |f|
f.select(:id,Comic.all,:prompt => true)
end %>
<img src="directory/<%= @comic.filename %>" />
<p class="title"><%= @comic.title %></p>
<p class="date"><%= 开发者_JS百科@comic.date %></p>
<% unless @prev.nil? %>
<a href="<%= @prev.id %>">Previous</a>
<% end
unless @next.nil? %>
<a href="<%= @next.id %>">Next</a>
<% end %>
The basic problem here is that the block tags you are using.
Rails uses two types of template tags: the <%=
ones are used for anything which should be evaluated and returned to the client, whereas the <%
would be used for control statements which do not return anything to the client.
Note also that anything in Rails 2 which is output with <%=
is not safely escaped, and you should probably be using <%= h @comic.title %>
(h for html escaping). However, if you use the plain <%=
syntax in Rails 3, it will handle the escaping for you.
You would probably do better to move to Rails 3 if you are learning the framework from scratch.
<% form_for ... do |f| %>
<%= f.select(...) %>
<% end %>
Edit: I suggest you also add <%= submit_tag %>
somewhere
I think the collection you are using needs a bit of formatting
f.select :id, Comic.all, :prompt => true
try
f.select :id, Comic.all.map { |c| [c.title, c.id] }, :prompt => true
# collection should resemble this format
[
["Batman", 1],
["Superman", 2],
...
]
精彩评论