在视图中显示关联模型的属性
我想获取在博客应用程序中创建文章的用户的用户名或电子邮件(都在用户表中)。 目前,我可以从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
文章表
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,但不知道如何用户名或电子邮件。 任何帮助,将不胜感激。
您已使用belongs_to :user
在Article
模型类上定义了user
关联。 这将在Article
上创建一个user
方法,返回关联的用户,以便您在视图中:
<%= article.user.email %>
将输出相关用户的电子邮件,或:
<%= article.user.email if article.user %>
以满足零用户价值。 或者写一个帮助器来将这个逻辑从视图中分解出来。
您已经在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
像这样你可以得到用户的所有属性。
- 有没有办法使用AREL进行自定义关联?
- Rails STI和has_many通过关联不起作用,SQLException:没有这样的表
- 在Rails查询中获取关联模型的属性
- belongs_to with:class_name选项失败
- has_many通过与现有对象/ ActiveRecord的关联
- 如何使用复选框应用带有acts_as_taggable_on的标签?
- 保存主对象时ActiveRecord是否保存belongs_to关联?
- Rails:ActiveRecord :: HasManyThroughSourceAssociationNotFoundError:找不到源关联
- 通过具有范围的关联保存时丢失属性(Rails 4.0.0)