0

简单的 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
4

1 回答 1

1

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

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

  #Rest of your code
end

这样,当您intro创建时,它将与发送者和接收者正确关联。然后,您将能够使用该方法访问 current_user 收到的介绍current_user.received_intros

您可能希望向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 %>
于 2012-06-29T02:51:21.457 回答