我的應用具有用戶模型和帖子模型,其中用戶has_many帖子和帖子belongs_to用戶。帖子顯示在用戶的個人資料頁面上。我希望任何用戶都能夠自己發佈帖子,或任何其他用戶的個人資料頁面。但是,我遇到的問題是,雖然我知道發佈的是誰(current_user),但我不知道其個人檔案current_user是否在使用。我需要知道這一點,才能將新帖子分配給該用戶的帖子。如何從當前正在查看的配置文件中提取用戶標識信息,以便我知道將新帖子分配到哪裏?Rails 3&Devise:跟蹤用戶帖子的擁有者配置文件
我的控制器,微柱看起來像:
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:未定義的方法`微觀柱的零:NilClass。我認爲這是因爲我在創建user_of_page變量時犯了一些錯誤,但我不知道那是什麼!
SOLUTION
感謝薩姆。我把你的意見,並最終做這樣的:
我添加了一個列到我叫belongs_to_id表微柱。
我然後通過其個人資料正在從用戶顯示視圖的微柱控制器在微柱形式使用隱藏字段中示出的用戶的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 %>
我然後使用這個值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
魔術!再次感謝您幫助我以正確的方式看到它。
User.find_by_name(params [:id])返回nil。重新檢查你是否有params [:id]! – 2011-03-01 04:17:11
就是這樣!我不知道我是否擁有它...我認爲它存在,因爲該行已成功用於我的用戶顯示視圖。也許我應該澄清一下:這是識別擁有目前正在查看的配置文件的用戶的正確方法嗎?我只想將micropost分配給您發佈的網頁的用戶,但我不知道如何識別該用戶 – Will 2011-03-01 04:31:47