gpt4 book ai didi

ruby-on-rails - 在 View 中显示关联模型的属性

转载 作者:数据小太阳 更新时间:2023-10-29 08:32:44 24 4
gpt4 key购买 nike

我想获取在博客应用程序中创建文章的用户的用户名或电子邮件(都在用户表中)。目前我可以从 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

但不知道如何获取相同的用户名或电子邮件。基本上我想在文章索引页面上显示用户名或电子邮件。请建议我如何完成它

用户.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

文章.rb

class Article < ActiveRecord::Base
attr_accessible :title, :body
has_many :comments
belongs_to :user
end

文章 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

我能够在 View 中获取用户 ID,但不知道如何使用用户名或电子邮件。任何帮助将不胜感激。

最佳答案

您已经在您的 Article 模型类上定义了一个 user 关联 belongs_to :user。这将在 Article 上创建一个 user 方法,该方法返回关联的用户,因此您在 View 中:

<%= article.user.email %>

将输出关联用户的电子邮件,或者:

<%= article.user.email if article.user %>

迎合零用户值(value)。或者编写一个帮助程序以将该逻辑排除在 View 之外。

关于ruby-on-rails - 在 View 中显示关联模型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15862365/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com