"update", :p-6ren">
gpt4 book ai didi

ruby-on-rails - 在 Controller 之间传递@variable

转载 作者:行者123 更新时间:2023-12-02 21:43:16 27 4
gpt4 key购买 nike

我的 ProjectProjectSetting 模型具有以下关联:

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 显示页面中使用 @project_setting 表单,并且我需要从此页面更新 @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

但是这些 Controller 中的@project变量并不相同:

projects_controller#show 中,它是 ID 为 26 的 Project,在 project_settings_controller#update 中,它找到 Project身份证号1

所以我需要将 @project 变量从 projects_controller#show 传递到 project_settings_controller#update

感谢您的帮助!

最佳答案

在 show.html.erb 中,您可以将变量传递回任何 Controller 。例如

<%= link_to "Update project setting", 
:controller => "project_settings",
:action => "update",
:project => @project %>

将发送填充有@project变量的参数“project”。

如果您在表单标记中,则可以发送带有隐藏字段标记的变量:

<% hidden_field_tag("project", @project) %>

我希望这会有所帮助。

关于ruby-on-rails - 在 Controller 之间传递@variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20019153/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com