[英]Rails - Associated model's show action & its corresponding view?
我正在構建一個具有典型用戶模型和配置文件模型的簡單應用程序。 用戶has_one配置文件和配置文件belongs_to用戶。 基本上我都在遵循Michael Hartl教程,因此一切似乎都工作得很好。 但是,當我嘗試渲染配置文件表中的某些內容的視圖(顯示動作)時,出現錯誤(無id),並且我創建的配置文件記錄被刪除!
問題:
在我的ProfilesController中,我是否為要渲染的簡單視圖正確定義了show動作?
為什么只訪問URL localhost / 3000 / profiles / 1會刪除配置文件記錄? 我認為這與從屬破壞有關(b / c刪除將停止此行為),但我想我想保持從屬破壞,對嗎?
路線
resources :users
resources :profiles
楷模
Class User < ActiveRecord::Base
has_one :profile, dependent: :destroy
Class Profile < ActiveRecord::Base
belongs_to :user
ProfilesController
def new
@profile = current_user.build_profile
end
def create
@profile = current_user.build_profile(params[:profile])
if @profile.save
flash[:success] = "Profile created dude!"
redirect_to root_path
else
render 'new'
end
end
def show
@profile = Profile.find(params[:user_id])
end
查看(profiles / show.html.erb)
<p>Display Name: <%= @profile.display_name %></p>
檢查您的rake routes
。 您會看到,對於Profile#show
,您具有如下URL結構: /profiles/show/:id
。
因此,params必須使用:id
而不是:user_id
。
如果要通過/profiles/show/3
來顯示配置文件3,則:
def show
@profile = Profile.find(params[:id])
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.