Rails render lookup value - ruby-on-rails

First: Enter a certain emp_no using the textfield.
Second: I am trying to render/show the lookup value from a table through .
Here's the view:
<div class="field">
<%= f.label :emp_no %><br />
<%= f.text_field :emp_no%>
</div>
<div class="field">
<%= f.label :emp_name %><br />
<div><label><%= #emp_name %></label></div>
</div>
Here's my controller:
before_filter :customer
def customer
#emp_name = where(Employee.params[:employee_code])
end
Any inputs are much appreciated! Thank you!

We've achieved something similar at http://firststopcosmeticshop.co.uk (try the search at the top)
Search
What you're looking for, simply, is a piece of functionality which helps you search your data.
This can be achieved relatively simply, but you have to make sure your syntax is correct:
#config/routes.rb
resources :employees do
get :search
end
#app/controllers/employees_controller.rb
class EmployeesController < ApplicationController
layout: Proc.new {|controller| controller.request.xhr? ? false : "application" }
def search
#emp_names = Employee.where code: params[:employee_code]
end
end
#app/views/employees/search.html.erb
<% #emp_names.each do |employee| %>
<%= employee.name %>
<% end %>
This setup will provide you with the ability to load the search items if you wanted to show them, allowing you both the ability to use ajax (detailed below), or just plain HTML / HTTP
Ajax
If you wanted to use Ajax to deliver "real time" results, you'll want to use the following details:
#app/assets/javascripts/application.js
$(document).on("ajax:success", "form", function(status, data, xhr){
$(this).append(data);
});
This should render the results wherever you want on your front-end (requesting) page. The trick lies in the controller's assertion of the layout depending on the type of request received (HTTP or XHR)
Form
Finally, your form needs to reflect the functionality you wish to define. Currently, you don't have any way to send the request to your emp_names method, and so you need to create a better way to manage it:
#view
<%= form_tag employees_search_path, remote: true do %>
<%= text_field_tag :input %>
<%= submit_tag %>
<% end %>
Of course, the form can change considerably, but it basically means that you will send a simple request to your employees_search_path, which will then give you the capacity to manage the response in the controller; either normally, or with Ajax

Related

Rails - Multiple forms, different Models (Objects), one submit button

I have a view with 3 forms, Schedules, Workouts and Exercises, all behaving like an edit form, each. And one submit(save) button in the all the view.
When I click on the save button. Every data changed on those forms should be updated after click.
What is the best solution for this ? Javascript updating each data separated ? How to do that ? Is there a more Rails way to do this easily ?
My difficulty is how to integrated all those models in one view, while all this is happening in the show(view) from the Student model.
If you're implementing something like a profile / edit page (where you can save all the records at once), the two ways I would look at would either be to save the forms via Ajax, or use a single submit method to handle them
Ajax
The ajax method would be the most conventional:
Every form you submit will go to the form's own update method in the backend
Each form could be handled by a single button, but it's best to split them up
#app/controllers/profile_controller.rb
def edit
#schedules = Schedule.all #-> not sure how many records you're using
#workouts = Workout.all
#exercises = Exercise.all
end
#app/views/profile/edit.html.erb
<%= form_for #schedule do |f| %>
<%= f.text_field :test %>
<% end %>
# -> other forms
<%= button_to "Save", "#", id: "save" %>
#app/assets/javascripts/application.js
$("#save").on("click", function() {
$("form").submit(); // we'll have to define the form to submit
});
Single
If you submit all the forms as one, you'll have to encase them all in a single form, as sending different errors. This could be achieved by using _, and handled in the backend by looping through the different params, saving each one individually.
I'd do this:
#app/controllers/application_controller.rb
def submit
types = %w(schedules exercises workouts)
for type in types do
type.constantize.update_attributes()
end
end
This allows you to create a form with the different data types submitted in the same action:
#app/views/profile/edit.html.erb
<%= form_tag profile_submit_path do %>
<%= fields_for #schedules do |f| %>
<%= f.text_field :title %>
<% end %>
# -> fields_for for the other objects
<% end %>
This will allow you to send the updated objects to your controller, allowing them to submit
If all of your models (Schedules, Workouts and Exercises) are associated, using fields_for should be a good option.
From the above link:
<%= form_for #person do |person_form| %>
First name: <%= person_form.text_field :first_name %>
Last name : <%= person_form.text_field :last_name %>
<%= fields_for :permission, #person.permission do |permission_fields| %>
Admin? : <%= permission_fields.check_box :admin %>
<% end %>
<%= f.submit %>
<% end %>
Read the guides.
You could have some simple javascript that iterates over all form tags and submits each of them.
Alternatively, if you are going to use javascript anyways, you could follow an AJAXish auto-save approach upon changing any field.
But I think it might be cleaner if you just had one form for multiple models, using fields_for.

Mentioning user username in comments (#mention) - Rails

In my rails app, if a user mentions another username in a comment by using the # character, such as #max i'm trying to add autocomplete to suggest a list of users and then automatically create a link_to (username, user_path(user)
This is what I have in my comment partial:
<%= form_for [commentable, Comment.new] do |f| %>
<%= hidden_field_tag :commentable_type, commentable.class.to_s %>
<%= hidden_field_tag :commentable_id, commentable.id %>
<p>
<%= f.text_area :body %>
</p>
<p><%= f.submit "Submit" %></p>
<% end %>
I'm trying to use this gem: https://github.com/ichord/jquery-atwho-rails
It says to bind the text area with
data = ['tom','john'];
$('textarea').atwho({at:"#", 'data':data});
Where do I actually put this? Can I do something like data = User.all? Should I just be using a regular expression to do this?
I think the reason that data = User.all isn't working is because User.all will return an array of User objects. What you want to do is retrieve those User object usernames (or whatever you want the autocomplete to use, and store that in data instead.
You might try something like
#usernames = User.pluck(:username)
to get all the usernames. Then, in your partial:
data = <% #usernames &>
$('textarea').atwho({at:"#", 'data':data});
This is assuming of course that your partial is an .erb file where you can embed ruby code.
You can do something like this:
<script>
data = <%= raw User.pluck(:username).compact.to_json %>;
$('textarea').atwho({at:"#", 'data':data});
</script>
You might want to move the loading of the usernames into the controller or a helper method. The whole sniplet might belong into an view partial to keep things organized. And it might not be the best idea to load all usernames into the view when there are too many users in the database.

Passing Input Text From text_field_tag as a variable for a URL...?

Okay, so I didn't know really how to word this correctly, but here is essentially what I am trying to do.
I am trying to take the text that a user inputs into my search box and pass it on to the URL.
Here is my view page so far:
<h1>What's the weather like by you?</h1>
<br />
<%= form_tag('http://api.wunderground.com/api/myAPIkey/conditions/q/**USER_TEXT_FROM_TEXT_FIELD_TAG**.json',:method =>
'get') do %>
<p>
<%= text_field_tag 'zipcode', params[:search] %>
<%= submit_tag "Check It Out!", :name => nil %>
</p>
<% end %>
I know this is probably such an easy thing to do, but I can't seem to find any way to correctly do it. Thanks for your help!
It looks like you are trying to redirect form submission to different url based on user input.
My no JavaScript sugestion would be to go through your own controller and redirect_to custom url. Something like this:
change your view to:
<h1>What's the weather like by you?</h1>
<br />
<%= form_tag('/weather') do %>
<p>
<%= text_field_tag 'zipcode' %>
<%= submit_tag "Check It Out!", :name => nil %>
</p>
<% end %>
create weather controller:
rails g controller weather create
add this line to your config/route.rb file:
match 'weather' => 'weather#create', via: :post
and modify you app/controllers/weather_controller.rb to look like this:
class WeatherController < ApplicationController
def create
redirect_to "http://api.wunderground.com/api/myAPIkey/conditions/q/#{params[:zipcode].split.join('+')}.json"
end
end
This isn't a nice solution and it isn't the smartest solution, it simply duplicates your code using rails stack. Your question doesn't give many information about what you would like to to with the date returned by api?? Do you really want to simply redirect to given url and see data as json?
I just try to give you another idea how to tackle this problem, its not a final solution.

Rails: Two Different Submit buttons in a form

I'm trying to create a simple form with two different submit buttons: one which will do a normal submit, and one which will do an ajax submit and render a partial. But I'm not sure how to do this because both go towards the same create action. I tried something like this:
/views/layouts/_form.html.erb:
<div id="theform">
<%= form_for(#user, :remote => true, :form_to_validate => 'user') do |f| %>
Name: <div id='name'><%= f.text_field :name %></div><br/>
Email: <div id='email'><%= f.text_field :email %></div><br/>
Phone Number: <div id='phone_number'><%= f.text_field :phone_number%></div><br/>
<%= f.submit "Normal Submit", name:'normal' %>
<%= f.submit "Ajax Submit" %>
<% end %>
</div>
app/controllers/user_controller.rb:
class UsersController < ApplicationController
def new
#user = User.new
end
def create
#user = User.new(params[:user])
if params[:normal]
render :partial => "layouts/user"
end
end
EDIT: this may seem like an odd task but it was an assignment given to me to demonstrate I could do it both ways. I know how to do the AJAX submit and the normal submit separately but my confusion is with having two submits in the form! :)
Why not write some JS that listens to the click or submit and you route it in JS if its ajax $.ajax to the ajax location else let it go through normally if its not and dont stop the propagation.
I don't think you need two submit buttons. Have the ajax button simply call the $.ajax method and send your data.
Alternately, you could have the ajax button call $('#formid').submit() after converting the form to be ajax, using whatever method you use to do so. This is probably the easier of the two methods.

Rails alternative to including active record call in view

I have a form partial that looks like this:
<%= form_for(#pool) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :tournament %><br />
<%= f.collection_select :tournament_id, Tournament.active, :id, :name, :prompt => true %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
This seems like a code smell because the view shouldn't be responsible for knowing how to get the data for the <select> tag. The alternative to have the controller assign an instance variable is problematic because I have to replicate that code in several actions depending on whether or not this form is rendered.
In ASP.NET MVC I'd just pull that field out into a partial view and display it with a call to RenderAction Which would evaluate a common controller action. However, in Rails render :action => '/view' seems to only allow full blown views to be rendered. I'm pretty new to Rails so I'm not sure about what the best practices are.
You can do a helper method as coder_tim suggests, but in my opinion that still leaves data access in the view.
The controller is the proper place for this and if you're worried about duplication, set up a before_filter that only acts on the actions that need this collection:
before_filter :get_active_tournaments, :only => [:new, :edit]
for example.
Hope this helps.
I like the smell of that code :) Simplicity over extremism. Less files = less methods to worry = cleaner code.
However, there are times when a dropdown is used too many times in your application, and it's a little more complicated than just calling a scope. In that cases, I write a helper.

Resources