我创建了一个具有以下属性的Micropost模型:
<Micropost id: 1, content: "test", user_id: 1, created_at: "2012-01-25 15:34:30", updated_at: "2012-01-29 11:07:53", title: "asdasdad">具有以下属性的用户模型:
<User id: 1, email: "alex@gmail.com", username: nil, etc...>以及具有以下属性的注释模型:
<Comment id: 1, content: "sdf", micropost_id: 1, user_id: nil, created_at: "2012-01-29 11:10:42", updated_at: "2012-01-29 11:10:42">到目前为止,我只完成了这一点:
micropost
F 216的链接)
编辑:
型号:
user.rb:
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,
:omniauthable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :username
has_many :microposts
has_many :comments
def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
data = access_token.extra.raw_info
if user = User.where(:email => data.email).first
user
else # Create a user with a stub password.
User.create!(:email => data.email, :password => Devise.friendly_token[0,20])
end
end
endmicropost.rb:
class Micropost < ActiveRecord::Base
attr_accessible :title, :content
belongs_to :user
has_many :comments
endcomment.rb:
class Comment < ActiveRecord::Base
attr_accessible :content, :user_id
belongs_to :micropost
belongs_to :user
end微站控制器:
controllers/microposts.rb
def show
@micropost = Micropost.find(params[:id])
end
def new
@micropost = Micropost.new
end
def create
@user = current_user
@micropost = @user.microposts.new(params[:micropost])
@micropost.save
redirect_to @micropost
end有什么建议来做到这一点吗?
发布于 2012-01-30 10:01:34
若要链接到您可以使用的用户,请执行以下操作
<%= link_to comment.user.username, comment.user %>一般来说,"Rails魔术“的一部分是,如果您正确地设置了一个关联,您就可以通过点符号访问相关的对象。这意味着,您不需要说comment.user_id,而是直接选择关联的用户对象,例如comment.user.username或comment.user.email .你的想法是:)
为了达到这个目的,你应该建立这样的模型:
class User < ActiveRecord::Base
validates_presence_of :username #username should obviously not allow nil values
has_many :microposts
has_many :comments
end
class MicroPost < ActiveRecord::Base
belongs_to :user
end
class Comment < ActiveRecord::Base
belongs_to :user
end发布于 2012-01-30 10:03:02
# Link:
=link_to "User profile", user_path(comment.user)
# Name of the author
=comment.user.username或者因为user_id在Micropost和Comment中都有
# Link:
=link_to "User profile", (@micropost.user)
# Name of the author
=@micropost.user.usernamehttps://stackoverflow.com/questions/9061954
复制相似问题