Hidden Field in Simple Nested Form Not Being Submitted - ruby-on-rails-3

Environment: Rails 3.1.0, Ruby 1.9.2
I have Portfolio model which has_many Positions which has_one Asset.
This is the schema for the Position model:
create_table "positions", :force => true do |t|
t.integer "portfolio_id"
t.integer "asset_id"
t.decimal "holding_percentage"
end
When the user creates a portfolio he/she should enter the portfolio name and then add positions by adding stock tickers. Jquery does its stuff and shows the full name of the asset and also inserts the asset_id into the hidden field.
I am using both nested_form and simple_form as follows:
<%= simple_nested_form_for #portfolio do |f| %>
<%= f.input :name, :placeholder => 'Your portfolio name' %>
<%= f.fields_for :positions do |position_form| %>
<%= text_field_tag 'asset-ticker', nil, :class => 'asset-ticker' %>
<span class="asset-name"></span>
<%= position_form.text_field :holding_percentage, :class => 'asset-perc' %>
<%= position_form.hidden_field :asset_id, :class => 'asset-num', :as => :hidden %>
<%= position_form.link_to_remove "Remove this position", :class => 'asset-rem-link' %>
<% end %>
<p><%= f.link_to_add "Add a Position", :positions, :class => 'asset-add-link' %></p>
<%= f.button :submit %>
<% end %>
The problem is that the asset_id value in the hidden field is not being submitted. The parameters look as follows:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"hmvoGHF9GzpPsohQQ2MwhWk4FzhVVrf+IqoChHgftEs=",
"portfolio"=>{"name"=>"needhelpnow",
"positions_attributes"=>
{"new_1316730954406"=>{"holding_percentage"=>"11", "asset_id"=>"", "_destroy"=>"false"},
"new_1316730961085"=>{"holding_percentage"=>"22", "asset_id"=>"", "_destroy"=>"false"},
"new_1316730971587"=>{"holding_percentage"=>"33", "asset_id"=>"", "_destroy"=>"false"}}},
"commit"=>"Create Portfolio"}

It turns out that the problem was that I was writing in the value of the hidden field with:
('.asset-num').html(data.id)
Instead of:
('.asset-num').val(data.id)

Related

Rails creating a collection without an association

What is the best and correct way to setup a simple_forms_for field that contains a collection for a select field but the values to be contained in the select need to be sourced from a model that does not have a direct association to the calling fields model?
For example I have a simple_forms_for form like follows:
<%= simple_form_for(#customer) do |f| %>
<%= f.error_notification %>
<fieldset>
<div class="form-inputs">
<%= f.input :code, required: true %>
<%= f.input :name, required: true %>
<%= f.input :location, required: true %>
<%= f.input :service_level %>
<%= f.input :golive_date, :as => :date_picker %>
<%= f.input :connection_type %>
<%= f.input :service_centre %>
<%= f.input :end_date, :as => :date_picker %>
<%= f.input :sla %>
<%= f.input :project_code %>
</div>
<div class="form-actions">
<%= f.button :submit, :class => "btn btn-primary" %>
</div>
</fieldset>
<% end %>
I want to make the :service_level field a selection field and add a collection to it, however the table that stores the lookup values is not associated with the Customer table for the form.
class Lookup < ActiveRecord::Base
validates_presence_of :name, :description
has_many :lookup_values
accepts_nested_attributes_for :lookup_values, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end
class LookupValue < ActiveRecord::Base
belongs_to :lookup
end
class CreateLookups < ActiveRecord::Migration
def change
create_table :lookups do |t|
t.string :name
t.string :description
t.timestamps
end
end
end
class CreateLookupValues < ActiveRecord::Migration
def change
create_table :lookup_values do |t|
t.integer :lookup_id
t.string :name
t.string :value
t.timestamps
end
end
end
I basically want to be able to populate the values of the select using the following SQL query:
select v.name||' - '||v.value
from lookup_values v,
lookups l
where v.lookup_id = l.id
and l.name = 'Service level';
The actual value that is saved into the :service_level field needs to be the value of v.name.
All of the collections examples I have seen only appear to show how to create selects based on models that have an association between them, just wondering if there is an easy way to achieve this without an association.
Ok, well this is embarrassing...
Simple solution was to modify the _form.html.erb view file so that the :service_level field reads as:
<%= f.input :service_level, :collection => LookupValue.joins(:lookup).where(lookups: { :name => 'Service level' }).pluck(:name) %>
I probably need to make this more DRY when repeating for multiple lookup values in the form.
Any ideas how I can enhance this code to:
Remove the blank value that is listed in the select field drop down?
Modify the value text that displays in the select drop down to be
Name ||' - '||value. For example show the values in the format
"L1 - Level 1". The actual value selected and saved would need to
remain as "L1" (the :name value)

How to save to two tables from one form in Rails

I have a regular form for User information which starts like so:
<%= form_for(#user, :html => { :class => "form-horizontal" }) do |f| %>
<%= f.text_field :last_name %>
...
<%= f.submit "Submit", class: "btn btn-primary", :name => "submit_button" if #user.last_step? %>
<% end %>
I also have some non User fields in the form. Here's an example:
<%= f.label "When is your birthday?" %>
<%= select_tag "month" %>
<%= select_tag "day" %>
<%= select_tag "year" %>
How would I save this to a different table than User?
If you want to update a model other than User, you should probably use accepts_nested_attributes_for and fields_for. The alternative is to just do the work in your create action of your UsersController, ie:
def create
#user = User.create params[:user]
#foo = Foo.find params[:foo_id]
#foo.date = Date.new(params[:foo_year], params[:foo_month], params[:foo_day])
...
end

Passing Rails Parameters into Form

I'm trying to pass in two variables for a Nested Model form to use, but I'm getting an error. It's probably an easy syntax error that someone experienced could see right away, but I don't see it.
I have a template showing users, if you click one, it should take the user_id and community _id for use in the form. Both community and user are properly declared in the controller.
link to form:
<%= link_to "award badge", award_badge_badges_path, :user_id => user.id, :community_id => #community.id %>
The form uses two models - badge and badge winners. The user_id and community_id are needed for badge_winners which is nested in badges. The error I'm getting is "undefined local variable or method 'user_id' for #<#<Class:0x77544c0>:0x7714230>" so I think that something is wrong with the 2nd and 3rd lines in the form. Here's the form:
<%= form_for(#badge) do |f| %>
<%= f.hidden_field :user_id ,:value => user_id %>
<%= f.hidden_field :community_id ,:value => community_id %>
<%= f.label :Description %>
<%= f.text_area :description %>
<%= f.fields_for :badge_winners do |builder| %>
<%= render "badge_winner", :f => builder, :locals => {:user_id => user_id, :community_id => community_id} %>
<% end %>
<%= f.submit "Give Badge" %>
<% end %>
the show template in the controller:
def award_badge
#badge = Badge.new
badge_winners = #badge.badge_winners.build
end
the badge winner partial
<%= f.hidden_field :user_id ,:value => user_id %>
<%= f.hidden_field :community_id ,:value => community_id %>

Formtastic nested form field not building has_one association?

Given a User who can possibly be an Artist:
class User < ActiveRecord::Base
has_one :artist
end
I've got a User & Artist nested form (using Formtastic gem):
<h1>Artist registration</h1>
<% #user.build_artist unless #user.artist %>
<%= semantic_form_for #user, :url => create_artist_path do |f| %>
<%= f.inputs :username %>
<%= f.semantic_fields_for :artist do |a| %>
<%= a.input :bio %>
<% end %>
<%= f.buttons do %>
<%= f.commit_button 'Register as Artist' %>
<% end %>
<% end %>
The problem is the :artist fields are not rendered.
I've also tried f.inputs :for => :artist do |a|.
For some reason, using #user.build_artist does not display the artist's fields in the form. If I try #user.artist = Artist.new I get an error, because it tries to save the Artist and validation fails.
How should I initialize the Artist model so I get the benefit of formtastic generators in a nested form? (Note that #user here is not a :new_record?)
Did you remember to set accepts_nested_attributes_for :artist in user.rb?

How do you pass rails 3 forms params into an array?

I have a nested form (using accepts_nested_attributes_for in respective models):
<%= form_for(:technician, :url => {:controller => 'pos', :action => 'create_ticket'}) do |f| %>
<%= f.fields_for :service do |s| %>
<%= s.text_field :name %>
<%= s.text_field :name %>
<%= s.text_field :name %>
<%= s.text_field :name %>
<% end %>
<% end %>
This works fine if I only have one s.text_field. But once I add additional text_fields, it doesn't run properly. If you look at the source code, the id and name are the same for all six?
How do I put these params into an array? [so that I can isolate them like this:]
service1 = Service.named(params[:technician][:service][1][:name])
(I've tried the method described on railscasts episode 192, but it didn't work either).
After hours of trial and error, I've hacked something that works (but please let me know if you know a better, more eloquent way):
in view:
<%= form_for(:technician, :url => {:controller => 'pos', :action => 'create_ticket'}) do |f| %>
<% for #i in 1..6 do %>
<%= f.fields_for "services[#{#i}]" do |s| %>
<% end %>
<% end %>
<% end %>
in controller:
for i in 1..6 do
#service = Service.named(params[:technician][:services][i.to_s][:name]).first
end
make sure you turn i into string