调用Javascript函数时是否可以更改Params哈希值? 我有一个隐藏的Div,说DIV1根据选择字段中的选定值变为可见,在DIV1中,我有一个只读文本字段,其值设置为辅助方法返回的值。
这个帮助器方法使用了一个动态的find_by,它取决于Params的值,但我猜param Hash在select的值改变时不会改变(因为它不是整页刷新?)。请问,如何实现更新,以便当选择值更改时,新值将反映在params散列中。我在form_for标签中有:remote => true。有没有比我更好的方法?
rails视图中的Select字段
#finance_year
<%=f.select :financeyear, options_for_select(finance_year),{ :include_blank => 'Select a
Financial Year' } %>
和该选择的onchange事件
jQuery ->
$('#finance').hide()
value = "Select a Financial Year"
$('#finance_financeyear').change ->
selected = $('#finance_financeyear :selected').text()
$('#finance').show()
$('#finance').hide() if selected is value
辅助方法
def amount_owed(student)
financeyear = params[:financeyear]
@thisstudent = Finance.find_last_by_user_id(@student.user_id,
:conditions => {:financeyear => financeyear } )
if(@thisstudent)
@amount_owed= @thisstudent.amount_owed
else
student.department.amount
end
end
我感谢任何帮助,我希望我能够聪明地提出这个问题。
答案 0 :(得分:2)
答案是AJAX。
首先,我们需要添加一条到config/routes.rb
的新路线,以使amount_owed()
成为真正的行动:
get '/finance_years/amount_owed/:student_id/:financeyear' => "finance_years#amount_owed"
接下来,只要调用amount_owed()
操作,我们就会创建一个默认视图:
<强> /app/views/finance_years/amount_owed.html.erb 强>
<%= @amount_owed %>
所以,那部分很容易。现在我们需要编辑amount_owed操作,以便它可以使用我们的参数:
<强> /app/controllers/finance_years_controller.rb 强>
def amount_owed(student)
financeyear = params[:financeyear]
@thisstudent = Finance.find_last_by_user_id(params[:student_id],
:conditions => {:financeyear => financeyear } )
if(@thisstudent)
@amount_owed= @thisstudent.amount_owed
else
@amount_owed = student.department.amount
end
end
这样,我们可以通过params哈希传递财务年度和学生ID,并且每次都获得金额。现在,为了让我们的coffeeScript访问当前的student_id和finance_year变量,我将在视图文件中向表单添加几个隐藏字段:
<强> /app/views/finance_years/_form.html.erb 强>
<%= hidden_field_tag :student_id, @student_id %>
<%= hidden_field_tag :finance_year, @finance_year %>
最后一个技巧是编辑coffeeScript,每当选择框发生变化时都会触发异步GET请求。
<强> /app/assets/javascripts/finance_years.js.coffee 强>
$('#finance_financeyear').change ->
student_id = $("#student_id").val()
finance_year = $("#finance_year").val()
selected = $('#finance_financeyear :selected').text()
$('#finance').show() unless selected == value
$.get "/finance_years/amount_owed/#{student_id}/#{finance_year}", (response)->
$('#finance input[type=text]').load(response)
这就是我可以做的所有远离我的rails开发机器。如果出现其他问题,请告诉我。
答案 1 :(得分:1)
我不是专家,但你不能直接从javascript修改服务器端代码。您需要打电话给服务器(在表单提交或通过ajax请求),告诉服务器自行更新。
为了澄清,服务器代码负责页面的初始呈现,但是一旦呈现模板,它就不存在于客户端页面上。所以你不能直接从coffeescript / javascript修改它。您需要将请求发送回服务器以处理该问题。