Change hidden_field_tag name - ruby-on-rails

_form.html.erb
<% #subjectmodulelists.each_with_index do |modules,index| %>
<%= hidden_field_tag 'subjectModuleId'+index.to_s, modules.subject_module_id%><%= f.submit class:"btn btn-primary" %>
<% end %>
The above code I have in partial form actual field name was subject_module_id in my db. Here i changed to 'subjectModuleId'+index.to_s for store array of data.
I have following Error.
Mysql2::Error: Field 'subject_module_id' doesn't have a default value: INSERT INTO term_questions
Params passes Like:
"subjectModuleId0"=>"65", "subjectModuleId1"=>"66", "subjectModuleId2"=>"67",
In my controller
#question = TermQuestion.new
#question.subject_module_id = params[:subjectModuleId]
How I change the name into subject_module_id.
Thanks.

Pass array value to the hidden field
<%= hidden_field_tag 'subject_module_id[]', #subjectmodulelists.map(&:subject_module_id) %>
<%= f.submit class:"btn btn-primary" %>
This way you will get params like
{ "subject_module_id"=>[65, 66, 67] }
Which then you can assign
#question.subject_module_id = params[:subject_module_id]

Related

Ruby on Rails | Collection_Select [Value] -> Param

Got a (hopefully) easy one:
Ruby partial view with a collection_select, need the value of that selection (var name = 'submod') passed as a param up to controller. Literally just stuck on how to get from collection_select/onchange() to named param.
html.erb code:
<% #modName = locals[:moduleName] %>
<% #id = locals[:id] %>
<%= form_with url: admin_command_path() do |f| %>
<%= collection_select(#refcode, :Code, Command.where(FLD: #modName), :Code, :Definition, options ={prompt: true}, html_options = {:onchange => "updateSubMod(this.value)"}) %>
<br /><br />
<button class="btn_new">
<%= link_to "Execute", new_admin_command_path(mod: #modName, submod: #refcode, id: #id) %>
</button>
<% end %>
The onchange function works as expected, so feel free to make use of that to solve for param:
<script>
function updateSubMod(Code) {
var submod = Code
console.log(submod, '********************')
}
</script>

Restriction in rails got error

I want to do:
If seller.accounting_acc then 'all state are possible', If seller doesn't have account_access then 'All state except sale/in-hand'
Here's my code:
<% if current_user.seller? && current_user.accounting_access? %>
<%= select_tag :set_state, options_for_select(state_options_for_seller, "comment"), class: "form-control set_state", id: "prospect_form_set_state" %>
<% else %>
<%= select_tag :set_state, options_for_select(state_options_for_seller, "comment", disabled: "sale"), id: "prospect_form_set_state" %>
<% end %>
I am stuck in this issue.
View:
<%= select_tag :set_state, options_for_select(state_options_for_seller(current_user), "comment"), class: "form-control set_state", id: "prospect_form_set_state" %>
Method (in the state model?), meta code, don't know the exact field names of course, so please adapt to your situation.
def state_options_for_seller(current_user)
if current_user.seller? && current_user.accounting_access?
return State.all
else
return State.where.not(state: 'sale')
end
end

Values of a book saved from amazon have {:value=>""} around it

I'm making an application where the user can search Amazon (with Vacuum) through my application for books, then be able to record the data of the book to their library.
When you search for a book, it goes through every result and puts each in a thumbnail. In every thumbnail there is a button that opens a modal with a form with hidden tags. When the user clicks the submit button, the book's title is saved into a new book. The only problem is that the title is saved like {:value=>"the title of the book that was saved"}
Here is the part of new.html.erb which has the search box:
<%= form_tag({controller: "books", action: "new"}, method: "get", id: "search-form") do %>
<%= text_field_tag :keywords, params[:keywords], placeholder: "Search for a book", class: "form-control" %>
<% end %>
Here is the part of new.html.erb which has the hidden form:
<% #results.each do |result| %>
…
<%= form_for #book do |f|%>
<%= hidden_field_tag :title, class: 'form-control', value: result.name %>
<%= f.submit "Add book", class: "btn btn-default green-hover" %>
<% end %>
…
<% end %>
Here are the new and create actions in my controller:
def new
#book = current_user.books.build if logged_in?
# Search actions
if params[:keywords]
request = Vacuum.new
request.configure(
aws_access_key_id: ENV['AWS_ACCESS_KEY_ID'],
aws_secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
associate_tag: 'my associate tag is here'
)
keywords = params[:keywords]
params = {
'SearchIndex' => 'Books',
'Keywords'=> keywords,
'ResponseGroup' => "ItemAttributes,Images"
}
raw_results = request.item_search(query: params)
hashed_results = raw_results.to_h
#results = []
hashed_results['ItemSearchResponse']['Items']['Item'].each do |item|
result = OpenStruct.new
result.title = item['ItemAttributes']['Title']
result.url = item['DetailPageURL']
result.image_url = item['MediumImage']['URL']
result.author = item['ItemAttributes']['Author']
result.pages = item['ItemAttributes']['NumberOfPages']
#results << result
end
end
end
def create
#book = #list.books.build(book_params)
if #book.save
flash[:success] = #book.title + "was added to your log."
redirect_to list_path(#book.list_id)
else
render 'books/new'
end
end
I tried to use gsub within book.rb to fix it, but that only changed the text within the flash message and it still saved as {:value=>"the title of the book that was saved"}.
after_create :init
private
def init
puts "Init was called!"
self.title.gsub!('{:value=>"', " ")
self.title.gsub!('"}', " ")
end
How can I change it so that it doesn't save the title with the {:value=>} around it?
I don't think the hidden field tag is right.
<%= hidden_field_tag :title, class: 'form-control', value: result.name %>
Try
<%= hidden_field_tag :title, result.name %>
Your title is being saved as a hash not a string. Use hash accessing methods:
t = title[:value]
puts t #=> "the tile of the book that was saved"

How would I go about adding a button id so I can tell which button has been pressed in Rails

I've got this bunch of code
<%= link_to admin_conference_statuses_path(conference_id: #conference.id), class: "btn btn-primary", method: :post, remote: true do %>
<span id="span">Comm invoiced out Venue</span>
<% end %>
<%= link_to admin_conference_statuses_path(conference_id: #conference.id), class: "btn btn-primary", method: :post, remote: true do %>
<span id="span">Cross charged to Client</span>
<% end %>
And I have this in my controller
def create
conference_id = params[:conference_id] #Keep the same
#conference_status = ConferenceStatus.find_by_conference_id(conference_id)#Keep the same
#conference_status = ConferenceStatus.new unless #conference_status#Keep the same
#conference_status.conference_id = params[:conference_id]
#conference_status.invoiced_out_user_id = current_user.id
#conference_status.invoiced_out_datetime = DateTime.now
if #conference_status.save
# Success
else
# Failure
end
end
Now, when one button is pressed it grabs the id and puts it into a database.
How would I go about adding it so that when button 2 (opposed to button 1) is pressed it puts current user id into a column called "cross_charged_user_id"
If you have the answer could you post it and explain what it does, so I know for next time?
Thanks
Sam
You can pass one extra parameter to second link. Then depending on this extra parameter you can assign the current user as cross_charged_user.
The html code look like:
<%= link_to admin_conference_statuses_path(#conference), class: "btn btn-primary", method: :post, remote: true do %>
<span id="span">Comm invoiced out Venue</span>
<% end %>
<%= link_to admin_conference_statuses_path(#conference, cross_site_to_client: true), class: "btn btn-primary", method: :post, remote: true do %>
<span id="span">Cross charged to Client</span>
<% end %>
And the controller just check the params[:cross_site_to_client] and assign the current user
if params[:cross_site_to_client].present?
#conference_status.cross_site_to_client_id = current_user.id
end
Even You can cleanup your code as well
#conference_status = ConferenceStatus.find_or_create_by_conference_id(params[:conference_id])
if params[:cross_site_to_client].present?
#conference_status.cross_site_to_client = current_user
else
#conference_status.invoiced_out_user = current_user
end
#conference_status.invoiced_out_datetime = DateTime.now
#conference_status.save

Rails display value based on key in deep array of hashes

This is the array of hashes received as parsed_response from an API response which was XML, using Httparty.
Difficult and confusing to traverse inside and get the value.
"flights"=>{
"flight"=>{
"segments"=>{
"segment"=>[ (this has square brackets)
{
"index"=>"3",
"departure_airport"=>"DEL",
"arrival_airport"=>"CCU",
"departure_date_time"=>"2014-07-07T13:20:00",
"arrival_date_time"=>"2014-07-07T15:35:00",
"flight_number"=>"20",
"airline"=>"AI",
"operating_airline"=>"AI",
"stops"=>"0",
"equipment"=>"320",
"duration"=>"8100"
},
{
"index"=>"4",
"departure_airport"=>"CCU",
"arrival_airport"=>"BLR",
"departure_date_time"=>"2014-07-07T18:10:00",
"arrival_date_time"=>"2014-07-07T20:40:00",
"flight_number"=>"771",
"airline"=>"AI",
"operating_airline"=>"AI",
"stops"=>"0",
"equipment"=>"319",
"duration"=>"9000"
}
]
}
}
},
To display above hash values I did
<% h["flights"]["flight"]["segments"]["segment"].each do |o,p| %>
<% if o.class == Hash %>
<strong><%= o['airline'] %></strong>
<%= o['arrival_airport'] %> - <%= o['arrival_date_time'] %><br>
<% else %>
<%= o %>
<% end %>
<% end %>
(NOTE: Simply placing o['airline'] after loop would give can't convert String into Integer)
The else statement is to parse the below type of response.
"flights"=>{
"flight"=>{
"segments"=>{
"segment"=>{ (no square brackets)
"index"=>"3",
"departure_airport"=>"DEL",
"arrival_airport"=>"CCU",
"departure_date_time"=>"2014-07-07T13:20:00",
"arrival_date_time"=>"2014-07-07T15:35:00",
"flight_number"=>"20",
"airline"=>"AI",
"operating_airline"=>"AI",
"stops"=>"0",
"equipment"=>"320",
"duration"=>"8100"
}
}
}
},
So having <%= o %> after else statment, will give
["index", "7"] ["departure_airport", "DEL"] ["arrival_airport", "BLR"] ["departure_date_time", "2014-07-10T07:10:00"] ["arrival_date_time", "2014-07-10T09:50:00"] ["flight_number", "807"] ["airline", "9W"] ["operating_airline", "9W"] ["stops", "0"] ["equipment", "738"] ["duration", "9600"]
But having <% elsif o=="departure_airport" %> <%= p %> <% end %> in-place of else statement, will give the value associated with the key.
To get a single value using the key, this is fine. But it really gets messy to put all those key in the above format to get their values.
There should be a better way to parse it, but just cant figure out how will I deduce a use case where ['segment'] would give the result appropriately, based on if it is again a hash or it is just a key.
Thanks.
The solution here would be to wrap the Hash into an Array before looping it.
controller
#segments_array = Array.wrap(h["flights"]["flight"]["segments"]["segment"])
view
<% #segments_array.each do |segment| %>
<strong><%= segment['airline'] %></strong>
<%= segment['arrival_airport'] %> - <%= segment['arrival_date_time'] %><br>
...
<% end %>
[h["flights"]["flight"]["segments"]["segment"]].flatten.each do |segment|
puts "#{segment['arrival_airport']} - #{segment['arrival_date_time']}"
end
HTH

Resources