开发者

Rails 3.0 - form_for and fields outside of the current model

开发者 https://www.devze.com 2023-03-30 15:47 出处:网络
When I submit a Photo to a Rails 3.0 photo gallery site. In addition to being able to upload the file, select Album from a drop down list, I need to be able to pass along a list of comma delimited tag

When I submit a Photo to a Rails 3.0 photo gallery site. In addition to being able to upload the file, select Album from a drop down list, I need to be able to pass along a list of comma delimited tags. I'm confused about the pr开发者_高级运维oper use of form_for. note: this is in the new.html.erb view (and new method of the PhotoController)

<%= form_for(@photo) do |f| %>
  <% if @photo.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@photo.errors.count, "error") %> prohibited this photo from being saved:</h2>

      <ul>
      <% @photo.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

    <%= f.label :album_id %>
    <%= select "photo", "album_id", @albums.map {|a| [a.name,a.id]} %><br />

    <%= f.label :name %>
    <%= f.text_field :name %><br />

    <%= f.label :photofile %>
    <%= f.file_field :photofile %><br />

    <%= f.label :tags %>
    <%= f.text_field :tags %><br />

   <%= f.submit %>
<% end %>

I'm confused about the proper way that I can (1) upload a file - am I headed down the right path with f.file_field. photofile isn't really a property of the Photo object. And (2) similar question with :tags - tags isn't a property on the Photo object so should it be f.text_field (3) I'm assuming the way I am doing the Album dropdown is correct (I hope?)


Remember you can create any fields inside the form_for, just like any other form.

The form for just helps you by generating fields with names like photo[name] but you can use a text_field_tag :tags and on the controller retrieve it with params[:tags] without a problem.

If the field is not from your model, you shouldn't use the f.<helper> just use another helper like text_field_tag appropriate for your data or even pure html if you'd like.


Firstly, you need to say :multipart => true in your form_for call. This says that the form has attachment. Then, for attachments, use a gem like paperclip or carrierwave. Checkout these railscasts for a nice introduction on how to use paperclip and carrierwave.

For tagging this railscast is a useful resource.

0

精彩评论

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

关注公众号