0

Simple 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

receivercurrent_userが作成したイントロにを割り当てることを許可しているようには見えませんか?ユーザーが有効なを設定できるようにフォームに入力する必要があります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 に答える