我们希望在我们网站上输入的每个微博具有Sender和Receiver属性。邮件的发件人,以及邮件的发送者。
换句话说,在每个用户看到的每个微博上,我们想要内容,并且只是在帖子内容的上方或下方,我们希望显示发送者和接收者。我们还希望用户能够点击发件人或收件人,并直接链接到该个人资料。
我们怎样才能做到这一点?我们对rails很新,并且认为需要在Micropost模型中进行添加才能使此更改生效。或者应该在MicropostsController中进行更改吗?
Micropost模型:
class Micropost < ActiveRecord::Base
attr_accessible :content, :belongs_to_id
belongs_to :user
validates :content, :presence => true, :length => { :maximum => 240 }
validates :user_id, :presence => true
default_scope :order => 'microposts.created_at DESC'
# Return microposts from the users being followed by the given user.
scope :from_users_followed_by, lambda { |user| followed_by(user) }
private
# Return an SQL condition for users followed by the given user.
# We include the user's own id as well.
def self.followed_by(user)
following_ids = %(SELECT followed_id FROM relationships
WHERE follower_id = :user_id)
where("user_id IN (#{following_ids}) OR user_id = :user_id",
{ :user_id => user })
end
end
MicropostsController:
class MicropostsController < ApplicationController
before_filter :authenticate, :only => [:create, :destroy]
def create
@micropost = current_user.microposts.build(params[:micropost])
if @micropost.save
flash[:success] = "Posted!"
redirect_to current_user
else
@feed_items = []
render 'pages/home'
end
end
def destroy
@micropost.destroy
redirect_to root_path
end
end
答案 0 :(得分:1)
为了消除一些混乱并使其变得更加困难,我会选择:
class Micropost < ActiveRecord::Base
belongs_to :sending_user, :class_name=>"User", :foreign_key=>"user_id"
belongs_to :receiving_user, :class_name=>"User", :foreign_key=>"belongs_to_id"
end
这将在您的视图中为给定的Micropost对象“@micropost”提供类似的内容:
<%= link_to(@micropost.sending_user.username, user_path(@micropost.sending_user)) %>
<%= link_to(@micropost.receiving_user.username, user_path(@micropost.receiving_user)) %>
*这假定了有关用户对象和路由的几个方面,但应该让您走上正确的道路。