在 Rails 3.2 中,我创建了一个后置控制器。每个帖子可以有不同数量的回形针附件。为了实现这一点,我创建了一个资产模型,其中每个资产都有一个回形针附件。一篇帖子有_许多资产和资产属于_to帖子。
资产模型
class Asset < ActiveRecord::Base
belongs_to :post
has_attached_file :photo, :styles => { :thumb => "200x200>" }
end
后模型
class Post < ActiveRecord::Base
attr_accessible :content, :title
has_many :assets, :dependent => :destroy
validates_associated :assets
after_update :save_assets
def new_asset_attributes=(asset_attributes)
asset_attributes.each do |attributes|
assets.build(attributes)
end
end
def existing_asset_attributes=(asset_attributes)
assets.reject(&:new_record?).each do |asset|
attributes = asset_attributes[asset.id.to_s]
if attributes
asset.attributes = attributes
else
asset.delete(asset)
end
end
end
def save_assets
assets.each do |asset|
asset.save(false)
end
end
end
帖子助手
module PostsHelper
def add_asset_link(name)
link_to_function name do |post|
post.insert_html :bottom, :assets, :partial => 'asset', :object => Asset.new
end
end
end
邮寄表格
<%= form_for @post, :html => { :multipart => true } do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content %>
</div>
<div id="assets">
Attach a file or image<br />
<%= render 'asset', :collection => @post.assets %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
资产部分
<div class="asset">
<% new_or_existing = asset.new_record? ? 'new' : 'existing' %>
<% prefix = "post[#{new_or_existing}_asset_attributes][]" %>
<% fields_for prefix, asset do |asset_form| -%>
<p>
Asset: <%= asset_form.file_field :photo %>
<%= link_to_function "remove", "$(this).up('.asset').remove()" %>
</p>
<% end -%>
</div>
大部分代码取自这里:https ://gist.github.com/33011 我知道这是一个 rails2 应用程序,无论如何我不明白这个错误意味着什么:
undefined method `new_record?' for nil:NilClass
Extracted source (around line #2):
1: <div class="asset">
2: <% new_or_existing = asset.new_record? ? 'new' : 'existing' %>
3: <% prefix = "post[#{new_or_existing}_asset_attributes][]" %>
4:
5: <% fields_for prefix, asset do |asset_form| -%>