<div class='comment'>
<p>
<%= comment.comment %>
<%= comment.user.email %>
</p>
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :user_name
t.string :full_name
t.string :email
t.string :password_digest
t.timestamps null: false
end
end
----------------------------------------------------------
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment].permit(:comment))
@comment.user_id = current_user.id
@comment.save
if @comment.save
redirect_to post_path(@post)
else
render 'new'
end
end
end
-------------------
class Comment < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
-------------------
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
validates :user, :presence => true
validates :title, :presence => true, length: { maximum: 25}, uniqueness: true
validates :content, :presence => true
end
-------------------
class User < ActiveRecord::Base
has_secure_password
has_many :posts
has_many :comments
def admin?
self.role == 'admin'
end
def moderator?
self.role == 'moderator'
end
validates :user_name, :presence => true, uniqueness: true
validates :full_name, :presence => true
validates :password, :presence => true
validates :email, :presence => true, uniqueness: true
end
--------------------
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.text :comment
t.references :post, index: true, foreign_key: true
t.references :user, index: true, foreign_key: true
t.timestamps null: false
end
end
end
它說undefined method user_name
你可以說,意見可能已經沒有USER_ID創建但那不是真正的因爲如果我寫<%= comment.user_id %>
它顯示正確的用戶ID。此外,所有評論都有用戶ID。 如果你可以請幫助,因爲我查了很多文件,但沒有發現任何東西。
到底什麼時候出現錯誤「未定義的方法user_name」? – MilesStanfield
你能粘貼完整的錯誤嗎? –
當我輸入顯示評論的帖子時,出現錯誤(即使在沒有錯誤的帖子上,我也會得到錯誤) –