回形针和嵌套属性问题
Posted
技术标签:
【中文标题】回形针和嵌套属性问题【英文标题】:paperclip and nested attributes problem 【发布时间】:2011-03-28 23:35:19 【问题描述】:使用回形针上传文件。我有项目、附件和关联表。我拥有可以上传文件的所有内容,但是当它进入项目控制器时,它会寻找方法attachment_file_name
,但是,我相信它应该是user_file_file_name
,因为:user_file
是附件模型用于has_attachment
语句。这是生产日志:
Started POST "/projects" for 136.152.181.137 at Mon Mar 28 16:23:28 -0700 2011
Processing by ProjectsController#create as html
Parameters: "commit"=>"Create Project", "authenticity_token"=>"xh0Ld2RKyJ6EF9jLNl3D+r1m50lKv389NCIor3H4fag=", "utf8"=>"?~\~S", "project"=>"name"=>"Upload Test", "icon_id"=>"1", "categories_attributes"=>"0"=>"name"=>"Category 1", "_destroy"=>"false", "content"=>"skee", "description"=>"description", "attachments_attributes"=>"0"=>"name"=>"name", "user_file"=>#<ActionDispatch::Http::UploadedFile:0x2aaaaf6b0fd8 @tempfile=#<File:/tmp/RackMultipart20110328-18838-4wasuv-0>, @headers="Content-Disposition: form-data; name=\"project[attachments_attributes][0][user_file]\"; filename=\"resized_DSCF0229.JPG\"\r\nContent-Type: image/jpeg\r\n", @original_filename="resized_DSCF0229.JPG", @content_type="image/jpeg">
Completed in 6ms
NoMethodError (undefined method `attachment_file_name' for #<Attachment:0x2aaaaf6a0638>):
app/controllers/projects_controller.rb:48:in `create'
app/controllers/projects_controller.rb:47:in `create'
如果有帮助,以下是模型:
class Project < ActiveRecord::Base
has_many :project_file_assocs
has_many :attachments, :through => :project_file_assocs
accepts_nested_attributes_for :attachments
attr_accessible :attachments_attributes
...
end
class Attachment < ActiveRecord::Base
has_attached_file :user_file
validates_attachment_presence :attachment
has_many :project_file_assocs
has_many :projects, :through => :project_file_assocs
attr_accessible :name, :description, :user_file_file_name, :user_file_content_type, :user_file_file_size
#attr_accessible :name, :description, :user_file
end
class ProjectFileAssoc < ActiveRecord::Base
belongs_to :attachment
belongs_to :project
end
它为什么要寻找那个方法?提前感谢您的帮助!
这里是projects_controller.rb的创建方法:
def create
@project = Project.new(params[:project])
respond_to do |format|
if @project.save
format.html redirect_to(@project, :notice => 'Project was successfully created.')
format.xml render :xml => @project, :status => :created, :location => @project
else
format.html render :action => "new"
format.xml render :xml => @project.errors, :status => :unprocessable_entity
end
end
end
【问题讨论】:
如果是生产日志,在开发环境中不会报同样的错误吗? 【参考方案1】:我认为问题出在附件模型中:
class Attachment < ActiveRecord::Base
has_attached_file :user_file
validates_attachment_presence :attachment
试试
validates_attachment_presence :user_file
【讨论】:
以上是关于回形针和嵌套属性问题的主要内容,如果未能解决你的问题,请参考以下文章
css基础 盒子模型border边框marginpaddingCSS分组和嵌套选择器Display(显示) 与 Visibility(可见性)Position 定位