听起来像是你应该建立两者之间的关系模型,或者说是你有什么了。
在创建方法只是这样做
@post = current_user.posts.create(params[:post])
这需要在前端没有现场和强制执行评论
听起来像是你的用户和他们的岗位
编辑之间的关系需要改变post.rb
belongs_to :user
到
belongs_to :sender, :class_name => "User"
编辑到架构
根据你的模型你只是存储发送/接收的字符串,因为这是你需要做的的情况是这样的:
in controller#create
@post = Post.create(params[:post])
@post.sender = current_user.username
编辑:这个怎么做正确
基于您的评论,它看起来像你想这样做在关系的方式,不错。
首先,对于您的文章,您需要将发件人和收件人更改为整数,然后分别重命名sender_id和receiver_id。
接下来在您的用户。RB模型,您需要具备以下条件:
has_many :sent_posts, :foreign_key => "sender_id"
has_many :received_posts, :foreign_key => "receiver_id"
在你post.rb模型,你需要具备以下条件:
belongs_to :sender, :class_name => "User"
belongs_to :receiver, :class_name => "User"
现在你可以做创建后
以下时
@post = current_user.sent_posts.create(params[:post])
而且可用以下方法
@post.sender #=> gets the sender
@post.receiver #=> gets the receiver
current_user.sent_posts #=> all posts from this user
current_user.received_posts #=> all posts for this user
注意我不能够验证这一点,但我敢肯定,上面应该为你工作,可能有一些轻微的错误,因为我目前不能仔细检查
我可能需要在另一个问题中提出这个问题,但是现在我得到了一个“未定义的方法`user_id ='for#”错误。我可能做错了什么? –
thoughtpunch
2011-01-24 18:50:58