0

私のアプリにはユーザーモデルと投稿モデルがあり、ユーザーには_多くの投稿があり、投稿は_ユーザーに属しています。投稿は、ユーザーのプロフィール ページに表示されます。すべてのユーザーが自分自身または他のユーザーのプロフィール ページに投稿できるようにしたいと考えています。ただし、私が抱えている問題は、誰が投稿しているのか (current_user) はわかっているものの、現在のユーザーのプロフィールが誰なのかがわからないことです。新しい投稿をそのユーザーの投稿に割り当てるには、これを知る必要があります。現在表示されているプロファイルからユーザー ID 情報を抽出して、新しい投稿をどこに割り当てるかを知るにはどうすればよいですか?

私のマイクロポストコントローラーは次のようになります。

class MicropostsController < ApplicationController
  before_filter :authenticate_user!

  def create
   @user_of_page = User.find_by_name(params[:id]) 
   @micropost = @user_of_page.microposts.build(params[:micropost])
    if @micropost.save
      flash[:success] = "Micropost created!"
      redirect_to :back
    else
      redirect_to about_path
    end
  end

  def destroy
  end
end

しかし、私は NoMethodError: undefined method `microposts' for nil:NilClass を得ています。これは、user_of_page 変数の作成を間違えたためだと思いますが、それが何であるかはわかりません。

解決

ありがとうサム。私はあなたのアドバイスを受けて、次のようにしました:

  1. 私は、belongs_to_id という名前の列を Micropost テーブルに追加しました。

  2. 次に、次のように、マイクロポスト フォームの非表示フィールドを使用して、プロファイルが表示されているユーザの ID をユーザ表示ビューからマイクロポスト コントローラに渡しました。

       <%= form_for @micropost do |f| %>
       <%= render 'shared/error_messages', :object => f.object %>
    
       <div class="field">
          <%= f.label :content, "Why that mood?" %>
          <%= f.text_area :content %>
       </div>
    
       <div class="field">
          <%= f.hidden_field :author, :value => current_user.name %>
          <%= f.hidden_field :belongs_to_id, :value => @user.id %>
      <%= f.hidden_field :agree, :value => "0" %>
      <%= f.hidden_field :disagree, :value => "0" %>
      <%= f.hidden_field :amused, :value => "0" %>
       </div>
    
       <div class="actions">
          <%= f.submit "Submit" %>
       </div>
     <% end %>
    
  3. 次に、この id 値を使用して、次のようにマイクロポスト コントローラーで投稿を割り当てるユーザーを検索します。

    class MicropostsController < ApplicationController
      before_filter :authenticate_user!
    
      def create
       @user_of_page = User.find(params[:micropost][:belongs_to_id]) 
       @micropost = @user_of_page.microposts.build(params[:micropost])
        if @micropost.save
          flash[:success] = "Micropost created!"
          redirect_to :back
        else
           redirect_to about_path
        end
      end
    
      def destroy
      end
    end
    

魔法!おかげさまで、正しい方法で見ることができました。

4

1 に答える 1

1

私は次のようにします:

class profiles_controller < AC
  ...
  def show
    @profile = User.find(params[:id]).profile || current_user.profile
    @post = Post.new       
  end
  ..
end

/profiles/show.html.erb
... 
Name: <%= @profile.full_name %> 
...
<%= form_for @post do |f| %>
  <%= hidden_field_tag @profile.user %>
  ...
<% end %>

class microposts_controller < AC
  def create
    profile_user = User.find(params[:user_id]) # Owner of the profile current_user is on
    ..
  end
end

未検証。お役に立てれば。

于 2011-03-01T05:23:38.247 に答える