Reputation: 5859
How do I pass those arguments which are not of model to a controller?
script.rb
class Script < ActiveRecord::Base
attr_accessor :directory
attr_accessor :xmlFile
end
show.html.erb
<h1><%= @script.Name %></h1>
<%= simple_form_for @script, :url => script_execute_path(script_id: @script.id) do |f| %>
<%= f.input :directory %>
<%= f.input :xmlFile %>
<%= f.button :submit, 'Run' %>
<% end %>
Here directory
and xmlFile
are used for taking inputs but it is not a part of Script
model. Now I need to pass values contained in directory and xmlFile to my execute
controller action
def execute
@script = Script.find(params[:script_id])
#something like this -- @xmlFile = params[:xmlFile]
end
how do I access it here?
Upvotes: 1
Views: 1305
Reputation: 4114
It looks like you've actually already figured it out. By declaring
attr_accessor :directory
attr_accessor :xmlFile
in your Script
model, you've effectively made them a part of the model. They just won't be persisted to the database when the object is saved. But as long as the object is in memory, those attributes will be available.
And since you've already got those attributes defined in your view:
<%= f.input :directory %>
<%= f.input :xmlFile %>
they'll be available to you in your controller via the params
hash via params[:directory]
and params[:xmlFile]
.
Upvotes: 1
Reputation: 2293
For arbitrary fields that aren't part of a model, you can use Rails' standalone tag helpers, such as text_field_tag
:
<%= simple_form_for @script, :url => script_execute_path(script_id: @script.id) do |f| %>
<%= text_field_tag :directory %>
<%= text_field_tag :xmlFile %>
<%= f.button :submit, 'Run' %>
<% end %>
If you want to pre-fill them with an existing value, you can pass that in as well:
<%= text_field_tag :directory, 'some default value' %>
Upvotes: 1
Reputation: 176402
They are indeed part of the Script
model, because they are defined as attributes of the model. The fact they are not persisted is irrelevant.
You access them from the hash of params that represent the model itself. You can determine the exact name inspecting the logs of the request, you'll see how the parameters are structured.
Assuming the name of the model is Script
, the hash key that contains the script attributes should be called script
, therefore:
params[:script][:directory]
Please note that Ruby doesn't use camelCase, therefore the name xmlFile
doesn't follow the conventions and may cause you issues. The name should be xml_file
, not xmlFile
.
Upvotes: 3