我正在构建一个具有典型用户模型的简单应用程序。个人资料模型。用户has_one个人资料和个人资料belongs_to用户。所有似乎都工作得很好,因为我基本上遵循Michael Hartl教程。但是,当我尝试从配置文件表中显示某些内容的视图(显示操作)时,我收到错误(无ID)并且我创建的配置文件记录被删除了!
问题:
在我的ProfilesController中,我是否正在为我想渲染的简单视图正确定义我的show动作?
为什么只访问网址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>
答案 0 :(得分:0)
检查rake routes
。您会看到,对于Profile#show
,您的网址结构如下:/profiles/show/:id
因此,params必须期待:id
而不是:user_id
。
如果按/profiles/show/3
,您希望显示个人资料3,则:
def show
@profile = Profile.find(params[:id])
end