在视图中显示相关模型的属性
问题描述:
我想要在博客应用程序中创建文章的用户的用户名或电子邮件(都在用户表中)。目前我能够从articles_controller.rb获取用户ID在视图中显示相关模型的属性
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
我能够在视图中获取用户ID,但是不知道怎么的用户名或电子邮件。 任何帮助,将不胜感激。
答
您已在Article
模型类中定义user
关联belongs_to :user
。这将创建在Article
一个user
方法返回相关的用户,以便您在您的视图:
<%= article.user.email %>
将输出相关的用户的电子邮件,或:
<%= article.user.email if article.user %>
迎合零用户的值。或者写一个帮手,将这种逻辑放在视图之外。
答
已经设置了文章&用户模型之间的关系。因此,在您的文章索引页中,您有@articles变量中的所有文章。所以,很容易就可以得到使用下面的代码特定物品的特定用户,
@articles.each do |article|
user = article.user #gives the user of this current article. From this
#objecct you can easily get the username, email or everything specific to user.
email = user.email #gives email of article's user or you can directly give artile.user.email
end
这样就可以得到用户的所有属性。当试图实现你的建议
+0
嗨Mohanrja,谢谢,我用得到了答案。 – 2013-04-07 14:13:03
嗨,我在文章得到NoMethodError#指数 显示F:/24/billi/app/views/articles/index.html.erb其中第12行提出: 未定义的方法'电子邮件'为零:NilClass错误。 – 2013-04-07 12:38:28
嗨史蒂夫,我是否需要更改我的articles_controller.rb文件中的代码。因为在文章控制器中创建操作,我获取当前用户标识但没有电子邮件。你有什么建议? – 2013-04-07 12:40:53
好吧,以便您的文章表中有一些没有设置user_id值的记录。您将需要防御性地围绕article.user返回nil。我更新了答案。 – Steve 2013-04-07 12:41:00