背景 - 我有2个模型,上传模型和用户模型。最初,我在上传模型(表)中拥有owner_id作为用户模型中用户标识的外键。然而,我不能让外键工作,所以我决定通过将owner_id重命名为user_id来使用“rails”方式。即使在将列设置为user_id之后,它也不会填充任何值。活动记录没有设置与has_many和belongs_to的外键
class User < ActiveRecord::Base
has_many :uploads
end
class Upload < ActiveRecord::Base
belongs_to :user
end
是否尝试过明确设置的关键,但它仍然无法在上传表
class User < ActiveRecord::Base
has_many :uploads ,:foreign_key => 'user_id'
end
填充USER_ID字段可能是简单的东西,但我不能似乎找到它是什么。有什么建议么 ?
**上传控制器
class UploadsController < ApplicationController
def index
@uploads = Upload.all
end
def new
@upload = Upload.new
end
def create
@upload = Upload.new(params[:upload])
if @upload.save
flash[:notice] = "your file has been uploaded"
redirect_to uploads_path
else
render :action => 'new'
end
end
def destroy
@upload = Upload.find(params[:id])
@upload.destroy
flash[:notice] = "Sucessfully deleted your file"
redirect_to uploads_path
end
def download
upload = Upload.find(params[:id])
#location = "#{Rails.root}"
# send_file (@upload)
#send_file('public/test_file.pdf', :filename => 'Test File', :type => 'application/pdf', :disposition => 'attachment', :streaming => 'true', :buffer_size => '4096')
send_file upload.uploaded.path,
:filename => upload.uploaded_file_name,
:type => upload.uploaded_content_type,
:disposition => 'attachment'
flash[:notice] = "Your file has been downloaded"
end
end
**上传表单
<%= form_for(@upload, :html => { :multipart => true }) do |form| %>
<form>
<fieldset>
<div class="clearfix">
<label for="fileInput">File input</label>
<div class="input">
<%= form.file_field :uploaded %>
</div>
<div class="actions">
<input type="submit" class="btn primary" <%= form.submit "Upload" %> <button type="reset" class="btn">Cancel</button>
</div>
</fieldset>
</form>
<% end %>
==架构信息
表名:用户
ID:整数不为空,主键
电子邮件:字符串(255)默认( “”),NOT NULL
encrypted_password:字符串(128)默认( “”),NOT NULL
reset_password_token:字符串(255)
reset_password_sent_at:日期时间
remember_created_at:日期时间
sign_in_count:整数默认(0)
current_sign_in_at:日期时间
last_sign_in_at:日期时间
current_sign_in_ip:字符串(255)**
last_sign_in_ip:字符串(255)
created_at:日期时间
的updated_at:日期时间
admin:布尔值默认(FALSE)
==模式信息-----------------------------------------
表名:上传
ID:整数
created_at:日期时间
的updated_at:日期时间
uploaded_file_name:字符串(255)
uploaded_content_type :字符串(255)
uploaded_file_size:整数
uploaded_updated_at:日期时间
USER_ID:整数
同时在这里发布用户模型和上传模型。 –
我认为问题出在窗体或控制器上,请粘贴两者。 – JCorcuera
用信息更新了我的问题。 – Skillachie