我正在尝试使用按钮更新我的Rails应用中的记录。我有一个用户,我想更新其school_id值。我有一个学校视图页面,用户可以单击按钮将该学校的ID添加到User school_id字段。我正在努力实施。这是我到目前为止所做的:
用户控制器:
def add_school
@user = User.find(params[:user_id])
@user.update_attributes(:school_id)
respond_to do |format|
flash[:notice] = "School has been added!"
format.html { redirect_to :back }
format.js
end
学校展示页面上的按钮:
<%= button_to "Add School", add_school_user_path, :method => "put" %>
我尝试通过向用户控制器中的更新操作添加代码以不同的方式执行此操作,但我无法使其工作:
def update
@user = User.find(params[:id])
if @user.update_attributes(params[:school_id])
flash[:notice] = "School has been added!"
redirect_to @user
end
if @user.update_attributes(params[:user])
flash[:notice] = "Successfully updated account and profile!"
end
end
将学校的ID传递到用户school_id列的最佳方法是什么?
谢谢!
编辑1:路线
resources :users do
member do
get :following, :followers
put :add_school
end
更新了控制器:
def add_school
@user = current_user
@school = School.find(params[:id])
@user.update_attributes(school_id: params[:school_id])
respond_to do |format|
flash[:notice] = "School has been added!"
redirect_to @user.school
end
end
更新了按钮链接:
<%= button_to "Add School", add_school_user_path(@user, school_id: @school.id), :method => :put %>
路由错误:
No route matches {:action=>"add_school", :controller=>"users", :school_id=>1, :id=>nil}
答案 0 :(得分:4)
你需要一个表格,而不仅仅是邻居
<%= form_tag add_school_user_path(@user), method: put do -%>
<%= hidden_field_tag :school_id, @school.id -%>
<%= submit_tag 'Add school' -%>
<%- end -%>
你没有提供上下文代码,也许@user和@school不是真正的变量名,但你可以从中得到这个想法
答案 1 :(得分:1)
您需要将整个哈希值传递给.update_attributes
的调用。
最好,您将school_id
放在user
内,所以看起来像
# params[:user] = { school_id: 1 }
@user.update_attributes(params[:user])
或者您可以手动编写学校ID
@user.update_attributes(school_id: params[:school_id])
或者,更好的是,验证关联
@user.school = School.find(params[:school_id]
您想要的路径是
user_add_school_path(@user, school_id: 1)
答案 2 :(得分:0)
这是一个古老的Q,但为了完整起见。您不一定需要一个表单来提交带有按钮/链接的简单形式的提交。您可以依赖jquery-ujs和 data-params 。
<%= link_to add_school_user_path(@user), class: "btn btn-xs btn-primary",
title: "Add school",
data: {remote: true, confirm: 'Are you sure?', method: 'put',
params: {user: {schoold_id: @school.id}}} do %>
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
Add school…
<% end %>
请注意,您希望控制器中的school_params
方法类似于params.require(:user).permit(:school_id)
答案 3 :(得分:0)
提供的答案不再完全准确。只要您不尝试传递任意数据,就可以通过button_to传递数据并更新记录。
button_to语法将是这样的-请注意,这是我的实现,并且未针对您的特定实现进行调整,因为您的控制器需要根据您为接受某些参数而做出的其他调整- -:
<%= button_to "Mark Completed", todo_path(todo.id),
params: {:todo => { :id => todo.id, :completed => true, :user_id => current_user.id }},
method: :put, data: { confirm: "Mark this To-Do as being completed? This will hide it from view." } %>