Rails Updating A Record - ruby-on-rails

I have database table called managers and here is the corresponding section for schema.rb
create_table "managers", force: true do |t|
t.string "fname"
t.string "lname"
t.string "company"
t.string "phone"
t.string "cell"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "plan_id"
t.string "country"
t.string "address"
t.string "timezone"
t.string "zipcode", default: "0"
t.datetime "open_time"
t.datetime "close_time"
t.integer "shifts"
t.integer "shiftlength"
end
In my controller I am trying to update it by calling the update action
def update
#manager=Manager.find(params[:id])
if #manager.update(manager_params)
redirect_to manager_path(:id=>params[:id])
else
render action: 'edit'
end
end
def manager_params
params.require(:manager).permit :fname,
:lname,
:company,
:country,
:address,
:timezone,
:zipcode,
:phone,
:cell,
:open_time,
:close_time,:shifts,:shiftlength
end
But the update action throws the following error
undefined method `each' for "4":String
The values :shifts and :shiftlength are being taken from number input fields. I tried to convert :shifts and :shiftlengths to integers using to_i but that did not work.
It then gave the error
undefined method `each' for 4:Fixnum
Relevant section of update form
<div class="form-group">
<%=m.label :number_of_shifts%><br />
<%= m.number_field :shifts,:class=>"form-control",:value=>#manager.shifts %>
</div>
<div class="form-group">
<%=m.label :shift_length%><br />
<%= m.number_field :shiftlength,:class=>"form-control",:value=>#manager.shiftlength %>
</div>

Related

Creating a drop down list from another table in rails

I am trying to add a relational field drop down select to the existing table. My current Schema
create_table "hardwares", force: :cascade do |t|
t.string "serialnumber"
t.string "modelnumber"
t.string "modeltype"
t.string "location"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "poc_id"
t.index ["poc_id"], name: "index_hardwares_on_poc_id"
end
create_table "pocs", force: :cascade do |t|
t.string "name"
t.string "address"
t.string "facility"
t.string "phone"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
The index field in the hardwares table was created when I ran the migration.
rails g migration addPocReferencesToHardwares poc:references
which generated the migration file below as well as the index in the schema
class AddPocReferencesToHardwares < ActiveRecord::Migration[5.1]
def change
add_reference :hardwares, :poc, foreign_key: true
end
end
After setting up the relationship, I would like to be able to select a POC for the hardware by name as a drop down of all available POC's.
I added this to the Hardware form:
<div class="field">
<%= form.label "POC" %>
<%= form.collection_select(:poc_id, Poc.all, :id, :name, { :prompt => 'Select a POC', :selected => #poc.poc_id }, { class: 'form-control' }) %>
</div>
The error I get is " undefined method `poc_id' for nil:NilClass". How do I allow a drop down selection for adding a POC to the hardware?
Issue was the fact that I had set the relationship as POC belongs to Hardware, thus in the Form field it needed to be:
<div class="field">
<%= form.label "POC" %>
<%= form.collection_select(:poc_id, Poc.all, :id, :name, { :prompt => 'Select a POC', :selected => #hardware.poc_id }, { class: 'form-control' }) %>
</div>

accessing attribute from other model in my search form

I'm a newbie and struggling a little with this:
I have two models: User & Job, the relationship is as follows:
class User < ApplicationRecord
has_many :jobs, dependent: :destroy
end
class Job < ApplicationRecord
belongs_to :user
end
In my jobs index view I have a search form where I want to locate jobs by address (ie: look for the User's address),
<%= form_tag(jobs_path, method: :get) do %>
<%= text_field_tag :address, params[:address] %>
<%= submit_tag 'Search', class:'btn btn-primary' %>
<% end %>
which is one of the user's attribute:
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.string "remember_digest"
t.boolean "admin", default: false
t.string "activation_digest"
t.boolean "activated", default: false
t.datetime "activated_at"
t.string "reset_digest"
t.datetime "reset_sent_at"
t.float "latitude"
t.float "longitude"
***t.string "address"***
t.string "phone"
t.index ["email"], name: "index_users_on_email", unique: true
end
In my JobsController, how do I point to the User's attributes? ie: User's address ? This is the index function I have for now:
def index
#jobs = if params[:address]
Job.where('address LIKE ?', "%#{params[:address]}%").paginate(page: params[:page], per_page: 20)
else
#jobs = Job.paginate(:page => params[:page], per_page: 4)
end
end
But obviously I'm not getting any thing when doing a search.
Thank you for your guiding advice in advance. Rodolphe
You should do something like:
Job.joins(:user).where(users: { address: address }) }

undefined method 'database field' for 'model'

error: thrown from the form
undefined method `profession_id' for #<DirectoryMember:0xa12be40>
env:
Rails: 5.0.0.1
Ruby: 2.2.4
form.html.erb
<%= f.collection_select(:profession_id, #professions, :id, :title, {:include_blank => true, :prompt => true}) %>
routes.rb
resources :directory_members
directory_members.rb
#professions = Profession.all.order(:title)
def directory_member_params
params.require(:directory_member).permit(
:user_id,
:directory_id,
:name,
:company,
:profession_id,
:address,
:phone,
:facebook,
:video,
:twitter,
:linkedin,
:google_plus,
:youtube
)
end
schema.rb
create_table "directory_members", force: :cascade do |t|
t.integer "user_id"
t.integer "directory_id"
t.string "name"
t.string "company"
t.text "address"
t.string "phone"
t.string "facebook"
t.string "video"
t.string "twitter"
t.string "linkedin"
t.string "google_plus"
t.string "youtube"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "profession_id"
end
I have ran rake db:migrate and all seems fine until the page is rendered.
Any clues as to why this is throwing the error would be awesome. Thanks

rails - form_for - how to have my 'Property' form update the 'Ticket' model?

I have 3 tables- OwnerofProperty , Property and Ticket. I want to make a form using form_for to represent property booking; can I make a form to retrieve data from Property where the submit button saves the data in the Ticket table? I am asking because I have no idea if that can be possible or how to make it.
Note: I have only created the relations :
OwnerofProperty one-to-many Property
Property one-to-one Ticket
I need this form just to make a user able to see the avaliable properties and can book only one , how to make this form ?
Schema.rb for the three models :
create_table "owners", :force => true do |t|
t.string "f_name"
t.string "l_name"
t.string "address"
t.string "tel_no"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "properties", :force => true do |t|
t.string "p_street"
t.string "p_city"
t.string "postcode"
t.string "property_type"
t.integer "rooms"
t.integer "rent"
t.integer "owner_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "properties", ["owner_id"], :name => "index_properties_on_owner_id"
create_table "tickets", :force => true do |t|
t.string "city"
t.string "street"
t.string "ticket_type"
t.integer "rooms"
t.integer "rent"
t.integer "property_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "tickets", ["property_id"], :name => "index_tickets_on_property_id"
Yes, it is possible.
let's see ticket_controller.rb
def new
#property = Property.find 20 #20 is property id
#properties = Property.all
##ticket = Ticket.new
end
now in view (where you want to create form):
<%= form_for #ticket do |f| %>
<%= f.select :property_id, #properties.collect {|p| [ p.name, p.id ] }%> <!-- just an example, Ticket model has a field named "property_id" -->
<%= f.submit %>
<%= end %>
this form submits to create action of ticket_controller. And you are able to get all data as params and save it to table.
def create
#ticket = Ticket.new(params[:ticket])
#ticket.save
respond_to do |format|
format.html{redirect_to( your_desired_path)}
end
end

Populate Rails Form With Model Information From Another Controller

I've renamed the SessionsController and Session Model to Periods/Period because it conflicted with Devise and so you'll see this in the update
I have a sessions and events model/controller. When a new session is created, it needs to be associated with a particular event.
In my sessions model, I have an event_id, but I want to have a dropdown on the form that is populated with name of non-past events. Once that is selected, the form should be able to assign the correct event_id to the created session.
What is the correct way to go about doing this?
Here is my schema.rb to help you get a clearer picture of what the Models look like:
ActiveRecord::Schema.define(:version => 20120807154707) do
create_table "events", :force => true do |t|
t.string "name"
t.date "date"
t.string "street"
t.string "city"
t.string "state"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "sessions", :force => true do |t|
t.string "name"
t.integer "event_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "users", :force => true do |t|
t.string "email", :default => "", :null => false
t.string "encrypted_password", :default => "", :null => false
t.datetime "remember_created_at"
t.integer "sign_in_count", :default => 0
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.boolean "admin", :default => false
end
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
end
Here is my form:
<%= form_for(#period) do |f| %>
<%= f.label :Name %>
<%= f.text_field :name%>
<%= f.label :Event %>
<%= f.collection_select(:period, :event_id, Event.all, :id, :name)%>
<%= f.label :time %>
<%= f.text_field :time, id: "timepicker" %>
<%= f.submit "Create Event" %>
<% end %>
and I keep getting the following error: undefined methodmerge' for :name:Symbol`
Breaking out the various arguments of collection select: f.collection_select(:period, :event_id, Event.all, :id, :name)
:period -> The object
:event_id -> the method I want to set on the object.
Event.All -> The collection (for now I'll take all of them)
:id -> the value of the html element option
:name -> the value displayed to the user
Am I doing that correct?
To display a select menu with options from another model (not another controller), try collection_select.
In your new Session form, this might look like:
collection_select(:event, :id, Event.where("date > :date", date: Time.now.strftime("%m/%d/%Y"))
In the Sessions controller, in the create action, build the association like this:
#session.event = Event.find(params[:event][:id])
I have found that this structure works for me:
<%= f.label :event %>
<%= f.collection_select :event_id, Event.all, :id, :name, {:prompt=> "Pick an Event"}, {:class => "form-control"} %>
The last bit was the html part which I used to set the Bootstrap class.
:name here could be :date or :street etc...

Resources