我有这个Pin模型:
class Pin < ActiveRecord::Base
belongs_to :user
belongs_to :image
accepts_nested_attributes_for :image
attr_accessible :image_attributes
end
我有这个图像模型:
class Image < ActiveRecord::Base
has_many :pins
validates_attachment_presence :attachment
validates_attachment_size :attachment, :less_than => 5.megabytes
validates_attachment_content_type :attachment, :content_type => ['image/jpeg', 'image/png']
accepts_nested_attributes_for :pins
attr_accessible :pins_attributes
end
为了创建一个新Pin我想使用图像的嵌套属性,但它不起作用:我在控制器和视图文件中使用的代码是:
def new
@pin = Pin.new
@pin.build_image if @pin.build_image.nil?
end
def create
@pin = Pin.new(params[:pin])
@pin.user_id = session[:user_id]
respond_to do |format|
if @pin.save
format.html { redirect_to(@pin, :notice => 'Pin was successfully created.') }
format.xml { render :xml => @pin, :status => :created, :location => @pin }
else
@boards = User.find(session[:user_id]).boards
format.html { render :action => "new" }
format.xml { render :xml => @pin.errors, :status => :unprocessable_entity }
end
end
end
在视图文件中:
<%= form_for @pin,:html=>{ :multipart => true} do |f| %>
<% if @pin.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@pin.errors.count, "error") %> prohibited this pin from being saved:</h2>
<ul>
<% @pin.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %>
<%= f.text_area :title %>
</div>
<%= f.fields_for :image do |f_i| %>
<div class="field">
<%= f_i.label :attachment %>
<%= f_i.file_field :attachment %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
所有时间表格都呈现错误:
Image attachment file name must be set.
答案 0 :(得分:3)
我想说问题在于Image模型中的attr_accessible :pins_attributes
和Pin模型中的另一个attr_accessible。通常除了id
之外的所有属性都可以访问(可以大量分配),但如果将属性声明为可访问 - 则必须列出要批量分配的所有属性。因此,尝试列出两个模型中的属性,或者只设置attr_accessible :all
答案 1 :(得分:1)
在Image模型中,我需要指定
has_attached_file :attachment, :styles => { :small => "150x150>" }
我的坏:(