我的Project
和ProjectSetting
模型具有以下关联:
class Project < ActiveRecord::Base
has_one :project_setting
end
class ProjectSetting < ActiveRecord::Base
belongs_to :project
end
在projects_controller
我有:
def show
@project = Project.find(params[:id])
@project_setting = @project.project_setting
end
所以我在@project_setting
展示页面中使用@project
表单,我需要从此页面更新@project_setting
。
在project_settings_controller
我有:
def update
@project = Project.find(params[:id]) #problem is here
@project_setting = @project.project_setting
if @project_setting.update_attributes(params[:project_setting])
respond_to do |format|
format.html { redirect_to project_path(@project) }
format.js
end
end
end
但这些控制器中的@project
变量不相同:
在projects_controller#show
中,Project
的ID为26,在project_settings_controller#update
中,它会找到ID为{1}的Project
所以我需要将@project
变量从projects_controller#show
传递到project_settings_controller#update
。
感谢您的帮助!
答案 0 :(得分:3)
在show.html.erb中,您可以将变量传递回任何控制器。例如
<%= link_to "Update project setting",
:controller => "project_settings",
:action => "update",
:project => @project %>
将发送填充了@project变量的参数“project”。
如果您在表单标记中,则可以使用隐藏字段标记发送变量:
<% hidden_field_tag("project", @project) %>
我希望,这有帮助。
答案 1 :(得分:2)
params[:id]
中的 project_settings_controller
包含@project_setting.id
如果你想从params获得@project.id
,你应该用routes.rb
嵌套路径写一下:
resources :projects do
resources :project_settings
end
然后在project.id
中提供了params[:project_id]
。
rails_guides