在某个用户处引导消息(' intros')

时间:2012-06-29 02:44:24

标签: ruby-on-rails ruby

简单的rails应用程序:我有2个模型,用户和介绍[这只是一个消息]。每条消息都有一个发送者(用户)和接收者(用户)。这是介绍模型(省略了验证):

class Intro < ActiveRecord::Base
  attr_accessible :content

  belongs_to :sender, class_name: "User"
  belongs_to :receiver, class_name: "User"

  default_scope order: 'intros.created_at DESC'
end

现在是用户模型:

class User < ActiveRecord::Base
    attr_accessible :name, :email, :password, :password_confirmation
    has_secure_password

    has_many :sent_intros, foreign_key: "sender_id", dependent: :destroy, class_name: "Intro"
    has_many :received_intros, foreign_key: "receiver_id", dependent: :destroy, class_name: "Intro"

    before_save { |user| user.email = email.downcase }
    before_save :create_remember_token

    private

        def create_remember_token
            self.remember_token = SecureRandom.urlsafe_base64
        end
end

该应用程序当前允许当前用户向表单提交介绍并与该消息关联(主页显示sent_intros)。但是,当涉及到received_intros函数时,我可以在intros_controller / create方法中使用一些帮助。如何让当前用户创建的介绍与另一个特定用户相关联(即发送给),以便我可以将其路由到收件人的收件箱?谢谢。

class IntrosController < ApplicationController
  before_filter :signed_in_user

  def create
    @sent_intro = current_user.sent_intros.build(params[:intro])
    if @sent_intro.save
        flash[:success] = "Intro sent!"
        redirect_to root_path
    else
        render 'static_pages/home'
    end
  end

  def index
  end

  def destroy
  end
end

1 个答案:

答案 0 :(得分:1)

看起来你不允许current_user将receiver分配给他们创建的介绍?您需要在表单上有一个输入,允许用户设置有效的receiver_id,并且您需要将receiver_id添加到attr_accessible:

class Intro < ActiveRecord::Base
  attr_accessible :content, :receiver_id 

  #Rest of your code
end

这样,当您创建intro时,它将与发件人和收件人正确关联。然后,您可以使用方法current_user.received_intros

访问current_user收到的内容

您可能需要为Intro模型添加一些验证,以确保接收者和发件人都存在。

编辑:您可以在评论中将receiver_id字段添加到您的代码中,如下所示:

<!-- In your first view -->
<% provide(:title, 'All users') %> 
<h1>All users</h1> 
<%= will_paginate %> 
<ul class="users"> 
  <%= @users.each do |user| %> 
    <%= render user %> 
    <%= render 'shared/intro_form', :user => user %>  <!-- make sure you pass the user to user intro_form -->
  <% end %> 
</ul> 
<%= will_paginate %> 

<!-- shared/intro_form -->
<%= form_for(@sent_intro) do |f| %> 
  <%= render 'shared/error_messages', object: f.object %> 
  <div class="field">  
    <%= f.text_area :content, placeholder: "Shoot them an intro..." %> 
  </div> 
  <%= observe_field :intro_content, :frequency => 1, :function => "$('intro_content').value.length" %> 
  <%= f.hidden_field :receiver_id, :value => user.id %> <!-- Add this to pass the right receiver_id to the controller -->
  <%= f.submit "Send intro", class: "btn btn-large btn-primary" %> 
<% end %>