2011-11-26 84 views
0

背景 - 我有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" %> &nbsp;<button type="reset" class="btn">Cancel</button> 
      </div> 


</fieldset> 
</form> 
<% end %> 

==架构信息

表名:用户

ID:整数不为空,主键

电子邮件:字符串(255)默认( “”),NOT NULL

encrypted_pa​​ssword:字符串(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:整数

+0

同时在这里发布用户模型和上传模型。 –

+1

我认为问题出在窗体或控制器上,请粘贴两者。 – JCorcuera

+0

用信息更新了我的问题。 – Skillachie

回答

1

在你的代码

class User < ActiveRecord::Base 
has_many :uploads ,:foreign_key => 'users_id' 
end 

users_id应该是user_id

+0

对不起,我在发布消息时发生了错字。我确实使用过'user_id'改正了我的文章,并包含了完整的模型。你认为我的控制器与user_id没有任何关系,即使关系是明确的吗? – Skillachie