我正在为API编写代码。我将参数分配给类字段。
我有关系, event_file.rb has_many :event_file_attachments
accepts_nested_attributes_for :event_file_attachments
event_file_attachment.rb
mount_uploader :attachment, EventFileUploader
belongs_to :event_file
想要从JOSN获取值并写入嵌套属性
JOSN,
{"event_files"=>{"event_id"=>"1"}, "attachment"=>#<ActionDispatch::Http::UploadedFile:0xc16e4e4 @tempfile=#<Tempfile:/tmp/RackMultipart20141226-5521-12zezuk>, @original_filename="asset.JPG", @content_type="image/jpg", @headers="Content-Disposition: form-data; name=\"attachment\"; filename=\"asset.JPG\"\r\nContent-Type: image/jpg\r\n">}
在控制器中,
data = params[:event_files]
@event_file = EventFile.new(:event_member_ids => data['event_member_ids'],
:user_id => current_user.id,
:company_id => @current_company.id,
:event_id => data['event_id'],
:status => 0)
@event_file.save
@event_file_attachment = EventFileAttachment.new(:event_file_id => @event_file.id,
:status => 0,
:attachment => params[:attachment])
@event_file_attachment.save
这是保存嵌套属性的错误方法,如何修改和优化代码....
答案 0 :(得分:1)
您创建的关联以及accepts_nested_attribute_for
方法将创建一个event_file_attachments_attributes
,您可以在其上添加相应的事件文件附件属性,这是一个简单的示例:
在控制器中:
@event_file = EventFile.new(:event_member_ids => data['event_member_ids'],
:user_id => current_user.id,
:company_id => @current_company.id,
:event_id => data['event_id'],
:status => 0,
:event_file_attachments_attributes => [{"0" => {:attr1 => "value", :attr2 => "value"}},{"1" => {:attr1 => "value", :attr2 => "value"}}])
有关此信息,您可以查看真正有用的railscast http://railscasts.com/episodes/196-nested-model-form-part-1