2014-12-13 47 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 
相关问题