Я хочу получить имя пользователя или адрес электронной почты (оба находятся в пользовательской таблице) пользователя, создающего статью в приложении для блога. В настоящее время я могу принести идентификатор пользователя из articles_controller.rbОтображение атрибутов для связанных моделей во взглядах
def create
@article = Article.new(params[:article])
@article.user_id = current_user.id
@article.save
redirect_to article_path(@article)
end
но не знает, как извлечь имя пользователя или адрес электронной почты для таких же. В основном я хочу отображать имя пользователя или адрес электронной почты на странице индекса статьи. Пожалуйста, предложите мне, как сделать, чтобы получить его
user.rb
class User < ActiveRecord::Base
has_many :articles
has_many :comments
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :username, :email, :password, :password_confirmation, :remember_me
attr_accessible :title, :body
end
article.rb
class Article < ActiveRecord::Base
attr_accessible :title, :body
has_many :comments
belongs_to :user
end
articles_controller.rb
class ArticlesController < ApplicationController
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
end
def new
@article = Article.new
end
def create
@article = Article.new(params[:article])
@article.user_id = current_user.id
@article.save
redirect_to article_path(@article)
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to action: 'index'
end
def edit
@article = Article.find(params[:id])
end
def update
@article = Article.find(params[:id])
@article.update_attributes(params[:article])
flash.notice = "Article '#{@article.title}' Updated!"
redirect_to article_path(@article)
end
end
статьи/index.html.erb
<div style="color:#666666; margin-top:10px"> <%= article.created_at %></div>
<div style="color:#666666; margin-top:10px"> <%= article.user_id %></div>
Статьи таблица
class CreateArticles < ActiveRecord::Migration
def change
create_table :articles do |t|
t.string :title
t.text :body
t.timestamps
end
add_index :articles, [:user_id, :created_at]
end
end
Я могу принести идентификатор пользователя в представлениях, но не знаю, как на имя пользователя или адрес электронной почты. Любая помощь будет оценена по достоинству.
привет, когда пытался реализовать ваше предложение, я получил NoMethodError в статьях # индекс Отображение F: /24/billi/app/views/articles/index.html.erb где линия # 12 поднял: неопределенный метод ' email 'for nil: ошибка NilClass. –
привет Стив, мне нужно изменить код в файле articles_controller.rb. потому что в создании действия в контроллере статьи я получаю текущий идентификатор пользователя, но не адрес электронной почты. Что ты предлагаешь? –
ОК, поэтому у вас есть записи в таблице статей, в которых нет набора значений user_id. Вам понадобится защитный код вокруг статьи, возвращающий нуль. Я обновил ответ. – Steve