2013-04-04 77 views
0

我想创建从发布到用户模型的关系。所以我创建:sqllite数据库中的关系没有外键添加

class Post < ActiveRecord::Base 
attr_accessible :text, :title, :image, :user_id 
has_many :comments 
belongs_to :user 
mount_uploader :image, ImageUploader 
end 

和User.rb:

class User < ActiveRecord::Base 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 
    attr_accessible :email, :password, :password_confirmation, :remember_me 
    has_many :posts 
end 

然后我将文件添加到数据库迁移:

class AddUserIdToPost < ActiveRecord::Migration 
    def change 
    add_column :posts, :user_id, :integer 
    end 
end 

并提出通过耙分贝迁移:迁移。

当我添加新帖子时,user_id(在dataBase中)的值为空,但列存在。 Post_Controller的

部分:

def create 
    @post = Post.new(params[:post]) 

    respond_to do |format| 
     if @post.save 
     format.html { redirect_to @post, notice: 'Post was successfully created.' } 
     format.json { render json: @post, status: :created, location: @post } 
     else 
     format.html { render action: "new" } 
     format.json { render json: @post.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

我应该怎么做@post = Post.new(PARAMS [:帖])?我认为一切都很好...

+0

您可能需要做':user_id''attr_accessible'在'POST'类 – 2013-04-04 16:48:17

+0

我加:user_id但没有任何改变。我检查数据库,并且我仍然在user_id上有空值(表格帖子) – Sawior91 2013-04-04 16:57:46

+0

你在哪里给'user_id'一个值?它在'params [:post]'里面吗? – 2013-04-04 17:04:23

回答

0
attr_accessible :text, :title, :image, :user_id 

,或者代替attr_accessible,只是这样做:

attr_protected 
+0

我添加了:user_id,但没有任何更改。我检查数据库,并且我仍然在user_id(表格帖子)上有空值。 – Sawior91 2013-04-04 17:27:12

+0

我不能让attr_protected becouse我得到错误:ActiveModel :: MassAssignmentSecurity :: ErrorControl在PostsController#创建“不能批量分配受保护的属性:标题,文本” – Sawior91 2013-04-04 17:38:46

+0

问题是与帕拉玛[:后] =>其添加表单中的所有字段。有没有用户的ID,所以它没有添加到数据库:) 问题链接: http://railsforum.com/viewtopic.php?id=38077 – Sawior91 2013-04-04 18:09:04