现在,我有两个模型:用户和微博。用户模型正在使用设计,设计。
所涉文件的示例:
user_controller.html.erb:
class PagesController < ApplicationController
def index
@user = current_user
@microposts = @user.microposts
end
endindex.html.erb:
<h2>Pages index</h2>
<p>email <%= @user.email %></p>
<p>microposts <%= render @microposts %></p>microposts/_micropost.html.erb
<p><%= micropost.content %></p>micropost.rb:
class Micropost < ActiveRecord::Base
attr_accessible :content
belongs_to :user
enduser.rg:
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现在,我想为微博发表一些评论:
current_user来做一些事情)。有什么建议来做到这一点吗?(对不起,我是Rails初学者)
发布于 2012-01-27 16:24:12
不,你说的一切都说明你需要多态关联。您需要的是一个具有模式的注释模型,如下所示:
create_table :comments do |t|
t.text :comment, :null => false
t.references :microposts
t.references :user
t.timestamps
end然后
# user.rb
has_many :microposts
has_many :comments
# microposts.rb
has_many :comments您可能需要为您的评论嵌套路由。所以,在你的routes.rb中,你会发现
#routes.rb
resources :microposts do
resources :comments
end。。在注释控制器中,是的,您将指定comment.user的值,如下所示.
# comments_controller.rb
def create
@comment = Comment.new(params[:comment])
@comment.user = current_user
@comment.save ....
end您可能想看看开始的Rails 3书,它将带您完成这个过程。
https://stackoverflow.com/questions/9029431
复制相似问题