2013-04-04 36 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