lat/long Coordinate insertion with form_for in Rails - ruby-on-rails

I'm using Rails 4.4.1, Ruby 2.1.2, RGeo 0.3.20 and activerecord-mysql2spatial-adapter 0.4.3
My problem is probably very simple since I'm new to both Ruby and Rails, but I could not find anything useful in the web so far.
I want to create a form to insert geo-spatial coordinates in my db, but I don't know how to access the :latlon fields x and y. This is my tentative code:
<h1>Inserimento nuova Città</h1>
<%= form_for #city, url: cities_path do |city| %>
<p>
<%= city.label :name, "Nome"%><br>
<%= city.text_field :name %>
</p>
<p>
<%= city.label :latlon, "Coordinate GPS" %><br>
<%= city.number_field :latlon.x %><br>
<%= city.number_field :latlon.y %><br>
</p>
<% end %>
The error I get when I access the localhost:3000/cities/new url is
undefined method `x' for :latlon:Symbol
Anyone knows how do I create a form to insert the latlon.x and latlon.y data in my db?

You can't call city.number_field :latlon.y because here :latlon is just a symbol - it's telling the helper to call the "latlon" method, and to set the name to "city[latlon]".
One way to get around this is to add get and set methods for the individual x/y values. These may exist already, added by the gem, i don't know as i've not used it. But you could add
class City < ActiveRecord::Base
def latlon_x
self.latlon.x
end
def latlon_y
self.latlon.y
end
def latlon_x=(num)
self.latlon.x = num
end
def latlon_y=(num)
self.latlon.y = num
end
Now you could say, in your form,
<%= city.number_field :latlon_x %><br>
<%= city.number_field :latlon_y %><br>
this will use latlon_x to get the value, and will cause latlon_x= to be called when you do #city.update_attributes(params[:city]) in your update action.

Related

Many-to-many is Rails

I'm doing backend for trello-clone app using Rails. I have board entity which has many column entities which are having many cards entities. I've made board-column part (using blog app example) and it works fine, but I can't understand how to make column-card part of that.
Method create in card controller is like:
def create
#board = Board.find(params[:board_id])
#column = #board.columns.find(params[:column_id])
#card = #column.cards.create(card_params)
end
I've made the form like this for adding cards for each column :
Form code:
<p>
<strong>Name:</strong>
<%= #column.name %>
</p>
<p>
<strong>Color:</strong>
<%= #column.background_color %>
</p>
<h2>Add a card:</h2>
<%= form_with(model: [#board, #column, #column.cards.build], local: true) do |form| %>
<p>
<%= form.label :name %><br>
<%= form.text_field :name %>
</p>
<p>
<%= form.label :description %><br>
<%= form.text_area :description %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>
So my question is how to make normal entity adding for the second level of the many-to-many relationship?
Your question is quite ambiguous but I guess you probably are confused about this thing:
Add hidden_field for board_id like:
form.hidden_field :board_id, value: #board.id
Then access it in the controller update/create with something like params[:column][:board_id] (check params to be exact) and relate the column with board id.
You surely are missing this piece but you surely are missing more.
I would suggest using byebug gem and inspecting params hash. It will help you a lot because I think you need to inspect params which are confusing you.
Another way (not good but simpler) to
puts "*"*100
puts params
puts "*"*100
as first line of create action in controller to see how exactly your params are. (Go into console and find whatever is written between 2 lines of asterisks in your server console)
Good Luck!

Storing user input value in controller

I have a controller named Welcome with view called index.
In my index view i have created a small form as such.
<%= form_for :location do |f| %>
<%= f.label :Longitude %><br>
<%= f.text_field :integer %>
<br>
<br>
<%= f.label :Latitude %><br>
<%= f.text_field :integer %>
<p>
<%= f.submit %>
</p>
<% end %>
In this form the user can enter some integer value for longitude and latitude. Once the user enters value for longitude and latitude. They click submit. Upon submit i would like to store these values in my controller. So i am using the following method where i have two instance variables taking values from the form.
def index
#long = params[:longitude]
#lat = params[:latitude]
end
In my routes.rb I have
get 'welcome/index'
post 'welcome/index'
Please tell me where i went wrong. Also if someone can suggest a better way of doing this also i would appreciate it i am new to rails and i want to learn the correct way of doing things so i don't create bad habits early on.
The reason it's not working is because your fields are both named :integer, and since they share the same name, the browser will only send one value.
So, with your code, if you filled in the first field with 'a' and the second with 'b', your params would contain something like this:
{ location: { integer: "aaa" } }
Which obviously isn't what you want! If your HTML looked more like this (I've stripped the layout stuff to make things clearer):
<%= form_for :location do |f| %>
<%= f.label :longitude %>
<%= f.text_field :longitude %>
<%= f.label :latitude %>
<%= f.text_field :latitude %>
<%= f.submit %>
<% end %>
Then you could access the params in your controller params[:location][:longitude] and params[:location][:latitude]
A good idea to see the difference between the effect of your form vs this form would be to inspect the html. Take a look at the input name attributes, and label for attributes and see how they match up with the params Rails receives. Also, when you post the form, be sure to look in your server log to see the params! :)
After reading your question, I think you want to see how controllers, views and models work. For learning purpose you can generate scaffold and study the generated code.
For example, generate a model GeoLocation, related controller and views by this:
rails g scaffold GeoLocation longitude:string latitude:string
Now fire up rails server and browse http://localhost:3000/geo_locations/new and save your long, lat. I wrote this answer to give you some guidance.
You can follow these excellent books:
The book of Ruby
The Rails 4 Way

Ruby on Rails access whole params hash

I have an application that deals with user rotas - and I'm currently adding the ability for admin approvals. If the user updates their own rota the params hash looks something like:
Parameters: {id:1, role_id: 1, team_id:1, rota: [startDate: 01/01/2014, endDate:02/02/2014]}
and these are submitted using a form with:
<%= form_for [#team,#role,#rota] do |f| %>
form code
<% end %>
We need to access the attributes outside the rota: object but currently can't find a way to as:
params.require requires you to pass an object in.
My team members have decided to add hidden fields to submit the attributes within the rota object but that seems redundant seeing as they are quite clearly there, we just can't find a way to access them, and ideas?
I was talking about something like
def user_rota_params
params.require(:user)
.permit(:role_id, :team_id, :rota => [:startDate, :endDate])
end
Then, for your nested attributes you could use fields_for.
Your form, thus, should look something this (omitting labels and keeping it basic):
<%= form_for #user do |f| %>
<%= f.text_field :role_id %>
<%= f.text_field :team_id %>
<%= f.fields_for :rota do |ff| %>
<%= ff.date_field :startDate %>
<%= ff.date_field :endDate %>
<% end %>
<% end %>

Ruby on Rails controller syntax

I am new to Rails, and just working my way through my first solo project, but I seem to be running into a syntax error with a constant not being initialized (Ive gotten several of these, but each seems to have a different cause.....not quite sure how i keep getting the same error with different causes :)):
uninitialized constant DatastringsController::Datastrings
DatastringsController:
class DatastringsController < ApplicationController
def new
end
def create
#datastrings = Datastrings.new(datastrings_params) #ERROR returned on this line
#datastrings.save
redirect_to #datastrings
end
def show
#datastrings = Datastrings.find(params[:id])
end
private
def datastrings_params
params.require(:datastrings).permit(:title, :text)
end
end
I believe my form is correct:
<%= form_for :datastrings, url: datastrings_path do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
The main problem you have is here:
<%= form_for :datastrings, url: datastrings_path do |f| %>
form_for really should be populated with an ActiveRecord object, as this allows Rails to build the relative paths it requires correctly.
Although I don't know why this is the case, your current setup is basically trying to render DatastringsController::Datastrings -- primarily because you've not set up your form_for correctly
--
Fix
If you want to create a datastring object, I'd follow convention and do this:
#config/routes.rb
resources :datastrings
#app/controllers/datastrings_controller.rb
Class DatastringsController < ApplicationController
def new
#datastring = Datastring.new
end
def create
#datastring = Datastring.new(datastring_params)
#datastring.save
end
private
def datastring_params
params.require(:datastring).permit(:title, :text)
end
end
#app/views/datastrings/new.html.erb
<%= form_for #datastring do |f| %>
<%= f.text_field :name %>
<%= f.submit %>
<% end %>
--
YOU ALSO NEED TO NAME YOUR MODELS IN SINGULAR
Looking at it now, it seems that your main issue is likely that you've named your model as a plural.
The reason this will be bad is that when you load Rails, it will load all your models, and consequently, allow you to call them by referencing their class name. If a model is plural, I don't think it will load it correctly, causing the error you've highlighted
If you name your model to the following, it should be better:
#app/models/datastring.rb
Class Datastring < ActiveRecord::Base
end

Titlecase all entries into a form_for text field

Trying to title-case all the entries from a form_for field so they're consistent going into the database for searches.
Here is my search field (file created as a partial):
<%= form_for #airport do |f| %>
Input city
<%= f.text_field :city, :value => f.object.city.titlecase %>
Input country
<%= f.text_field :country, :value => f.object.country.titlecase %>
<%= f.submit %>
<% end %>
But when I run it I get a NoMethodError:
undefined method 'titlecase' for nil:NilClass
I took instruction on the .object.city.titlecase from this post.
Can anyone help?
You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base
before_save do |place|
place.city = place.city.downcase.titleize
place.country = place.country.downcase.titleize
end
end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

Resources