2014-12-13 46 views
0

我有一個用戶模型:添加user_ids每篇文章(色器件)

devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_secure_password has_many :articles

而且我對User模式是這樣的:這些

create_table "users", force: true do |t| t.string "first_name" t.string "last_name" t.string "email" t.string "password_digest" t.datetime "created_at" t.datetime "updated_at" t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" end

一半是從色器件寶石。所以我試圖完成的是讓每篇文章都有一個作者(first_name + last_name)。

我的文章模型是這樣的:

belongs_to :topic 
belongs_to :user 

def author 
    "#{self.user_id.first_name} #{self.user_id.last_name}" 
end 

和我的文章控制器的操作是這樣的:

def create 
@article = Article.new(article_params) 
@article.user = current_user 
if @article.save 
    #@article.user = session[:user_id] 
    flash[:notice] = "Article has been uploaded" 
    redirect_to(:action => "show", :id => @article.id) 
else 
    flash[:notice] = "Please fill in all fields." 
    render("new") 
end 
end 

如果我在我的節目觀點做<p><%[email protected]%></p>,它有一個錯誤,指出undefined方法 - 'first_name'

如何爲每篇文章添加作者。

+0

而且,我不知道我是否應該在創建操作使用'@article.user_id = current_user'。 – xoshi827 2014-12-13 06:56:49

回答

0

使用self.user.first_name而不是self.user_id.first_name.in您筆者法
如果你想在這種情況下再
使用@ artilce.user_id OT使用USER_ID @ article.user = CURRENT_USER是罰款= current_user.id

+0

嗨。我現在有設計問題干擾我原來的代碼。我在'Access'控制器中有代碼: – xoshi827 2014-12-13 09:15:31

+0

'def attempt_login if params [:email] .present? && params [:password] .present? found_user = User.where(:電子郵件=> PARAMS [:電子郵件])。第一 如果found_user authorised_user = found_user.authenticate(PARAMS [:密碼]) 端 端 如果authorised_user 會話[:USER_ID] = authorised_user .id session [:email] = authorised_user.email flash [:notice] =「您已登錄」 redirect_to(:controller =>「articles」,:action =>'index') end' – xoshi827 2014-12-13 09:15:56

+0

我認爲它與您原來的問題無關。您可以通過這種方式解釋您現在面臨的問題,因爲形成這種方法和您的評論我無法得出任何結論...... – 2014-12-13 10:20:20

0

還好這裏是你如何做到這一點:

user.rb

has_many :items 

article.rb

belongs_to :user 

articles_controller.rb

def create 
    @article = Article.new(params[:article].permit(:name, ...)) 
    @article.user_id = current_user.id 
    if @article.save 
     flash[:notice] = 'article created' 
     redirect_to @article 
    else 
     render 'new' 
    end 
end 
相關問題