活动记录不使用has_many和belongs_to设置外键

时间:2011-11-26 04:33:55

标签: ruby-on-rails activerecord

背景 - 我有2个模型,一个上传模型和一个用户模型。最初我在上传模型(表)中有owner_id作为用户模型中用户id的外键。但是我无法使用外键工作,因此我决定通过将owner_id重命名为user_id来实现“rails”方式。即使将列设置为user_id,也不会填充任何值。

 class User < ActiveRecord::Base
has_many :uploads
end

class Upload < ActiveRecord::Base
belongs_to :user
end

尝试过显式设置密钥,但仍然没有填充上传表格中的user_id字段

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

可能是简单的东西,但我似乎无法找到它是什么。有什么建议 ?

**上传控制器

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:integer not null,主键

email:string(255)default(“”),not null

encrypted_pa​​ssword:string(128)default(“”),not null

reset_password_token:string(255)

reset_password_sent_at:datetime

remember_created_at:datetime

sign_in_count:整数默认值(0)

current_sign_in_at:datetime

last_sign_in_at:datetime

current_sign_in_ip:string(255)**

last_sign_in_ip:string(255)

created_at:datetime

updated_at:datetime

admin:boolean default(FALSE)

==架构信息-----------------------------------------

表名:上传

id:integer

created_at:datetime

updated_at:datetime

uploaded_file_name:string(255)

uploaded_content_type:string(255)

uploaded_file_size:integer

uploaded_updated_at:datetime

user_id:整数

1 个答案:

答案 0 :(得分:1)

在您的代码中

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

users_id应为user_id