首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建属于它们各自的微博和用户的评论(在一个应用程序中使用Devise)

创建属于它们各自的微博和用户的评论(在一个应用程序中使用Devise)
EN

Stack Overflow用户
提问于 2012-01-27 05:43:42
回答 1查看 244关注 0票数 0

现在,我有两个模型:用户和微博。用户模型正在使用设计,设计

所涉文件的示例:

user_controller.html.erb:

代码语言:javascript
复制
class PagesController < ApplicationController
  def index
    @user = current_user
    @microposts = @user.microposts
  end
end

index.html.erb:

代码语言:javascript
复制
<h2>Pages index</h2>
<p>email <%= @user.email %></p>
<p>microposts <%= render @microposts %></p>

microposts/_micropost.html.erb

代码语言:javascript
复制
<p><%= micropost.content %></p>

micropost.rb:

代码语言:javascript
复制
class Micropost < ActiveRecord::Base
  attr_accessible :content

  belongs_to :user
end

user.rg:

代码语言:javascript
复制
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me

  has_many :microposts
end

现在,我想为微博发表一些评论:

  • 每个评论应该属于其各自的微博和用户(评论)。不知道如何做到这一点(使用多态关联是一个好情况吗?)。
  • 用户应该有许多微博和评论(也不知道如何协调)。
  • 我不知道如何使评论成为当前登录的用户(我认为我必须使用Devise的current_user来做一些事情)。

有什么建议来做到这一点吗?(对不起,我是Rails初学者)

EN

回答 1

Stack Overflow用户

发布于 2012-01-27 16:24:12

不,你说的一切都说明你需要多态关联。您需要的是一个具有模式的注释模型,如下所示:

代码语言:javascript
复制
    create_table :comments do |t|
        t.text :comment, :null => false
        t.references :microposts
        t.references :user
        t.timestamps
    end

然后

代码语言:javascript
复制
# user.rb
has_many :microposts
has_many :comments

# microposts.rb
has_many :comments

您可能需要为您的评论嵌套路由。所以,在你的routes.rb中,你会发现

代码语言:javascript
复制
#routes.rb
resources :microposts do
    resources :comments
end

。。在注释控制器中,是的,您将指定comment.user的值,如下所示.

代码语言:javascript
复制
# comments_controller.rb
def create
    @comment = Comment.new(params[:comment])
    @comment.user = current_user
    @comment.save ....
end

您可能想看看开始的Rails 3书,它将带您完成这个过程。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9029431

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档