我有這個針型號:嵌套屬性belongs_to的關係
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.
檢查我的答案.. –
不錯,你發現問題 – alony
+1不錯的提示。非常感謝 –