convert string in a field name rails - ruby-on-rails

a need how convert string value in field name valid:
Example:
<%="price.list_"+current_user.price.to_s%>
so
price.list_1
then is my real field name. this name.this field will use it to do more operations in my view.

I think I understood your question. You will need to use the send function
<%= price.send("list_#{current_user.price}".to_sym) %>

That should work but you can also do
<%= "price.list_#{current_user.price.to_s}" %>
OR
<p>
price.list_<%= current_user.price.to_s %>
</p>
UPDATE: I misunderstood the question. This is going to require some Javascript or AJAX, depending on your exact application.
JS:
:onchange => 'update(this.value)'
function update(new_value) {
var update_me = document.getElementById('update_this_field');
update_me.value = new_value;
}
AJAX on RAILS
:onchange => remote_function(:url => {:action => 'update'}, :with => 'Form.element.serialize(this)'), :name => 'foo'
def update
bar = params[:foo]
render :update do |page|
page.replace_html 'update_this_field', "price.list_" + bar
end
end

Related

Rails: How to render repetitive form block?

In order to not repeat myself, I would like to create a function that render a form block (text field or text area) in a specific way. I want a result like this one (using Haml, and twitter-bootstrap):
.form-block.input-prepend
%span.add-on>
%i.icon.icon-home
= f.text_field :name, :value => #store.name, :placeholder => 'Company Name'
To do that, I created a file views/layouts/_form-block.html.haml where I inserted the following code:
.form-block.input-prepend
%span.add-on>
%i{ :class => "icon icon-#{icon}" }
= yield
And I call the block in my view using:
- render :template => 'layouts/_form-block', :locals => { :icon => 'home' } do
= f.text_field :name, :value => #store.name, :placeholder => 'Company Name'
But It doesn't work. I have the following error 'nil' is not an ActiveModel-compatible object that returns a valid partial path.
Do you have any idea? Is this the best way to do?
Thanks in advance.
If you want to use = yield to pass a block, you need to render as a layout. Use render :layout => instead of render :template =>.

How to get data from input field using ruby on rails

How to get data from an HTML text field and use it in RoR?
For example, let's say I enter a word in the text field and RoR prints how many characters are in said word.
Best way to do that is using the JAVASCRIPT but you insist for ROR use observe_field
<%= text_field :users, :word, :value=>'', :autocomplete=>'off' %><br>
<span id="word_message" style="color :red; font-size: 9px;"></span>
<%= observe_field :users_word, :url => { :action => :word_length, :id=>1 },
:on=>"blur",
:frequency => 0.25,
:with => "'word='+value" %>
In Controller
def word_length
word = params[:word]
render :update do |page|
page.replace_html 'word_message', "#{word.length} characters"
end
end

update_attributes with none-standard form

I have cobbled together a form due to some oddities in my code and routes. Things work for adding data to the database, but I can't quite seem to figure out how to update data. Here is some code.
new.html.erb
<% form_tag '/list' do %>
Episodes Completed:
<%= text_field_tag "completed" %>
Watch Status
<%= collection_select(nil, 'id', #show_status, :id, :state) %>
<%= hidden_field_tag('show_id', #show.id) %>
<%= submit_tag 'Add' %>
<% end %>
edit.html.erb
<% form_tag("/list/#{#show_completion.show.id}", :method => :put ) do %>
Episodes Completed:
<%= text_field_tag "completed", #show_completion.episodes_completed %>
Watch Status
<%= collection_select(nil, 'id', #show_status, :id, :state) %>
<%= hidden_field_tag('show_id', #show_completion.show.id) %>
<%= submit_tag 'Edit' %>
<% end %>
Here is the controller's Create and Update methods
def create
#show_completetion = ShowCompletionStatus.new
#show_completetion.user_id = current_user.id
#show_completetion.episodes_completed = params[:completed]
#show_completetion.status_state_id = params[:id]
#show_completetion.show_id = params[:show_id]
#show_completetion.save
end
def update
#show_completion = ShowCompletionStatus.find(params[:id])
#show_completion.episodes_completed = params[:completed]
#show_completion.status_state_id = params[:id]
#show_completion.show_id = params[:show_id]
if #show_completion.update_attribute('episodes_completed', params[:completed])
redirect_to "/list/#{current_user.username}"
else
redirect_to "/list/#{params[:id]}/edit"
end
end
Here are my routes for these:
match "list/" => "list#create", :via => :post
match "list/new/:show_id" => "list#new", :constraints => { :show_id => /[0-9]+/ }
match "list/:id/edit" => "list#edit", :constraints => { :id => /[0-9]+/ }, :via => :get
match "list/:id" => "list#update", :constraints => { :id => /[0-9]+/ }, :via => :put
I have been trying different things to get this to work for the better part of 4 hours now. I think I am just missing something, but I just can't see it.
Is there a better way to do the form that makes it work better?
Any help is appreciated.
I solved this issue by making a hash and passing it to the update attributes with the key value pairs of what the objects attributes would be. Since updates_attributes takes a hash and not an object it was a simple solution once the connection was made.
Try to replace your update_attribute call for a save call.
Also, if you're writing everything from scratch instead of using the builtins, try to use save! instead of save: it will raise an exception if it fails, unlike the plain save that just returns false.

Ruby on Rails Country/State Select Enigma

I am trying to implement something seemingly very simple, and I have been beating my head against it for days at this point.
My desired end result is a Country select drop-down, tied to a State select drop-down, in such a way that when a given country is selected, IF states are known THEN those states are displayed in a select drop down, and if NO states are known for that country, then a text field is displayed instead.
I feel like I am almost there. At this point the interface will actually generate that list of states based on the persons' country, except it is refusing to update the drop-down dynamically.
The portion of my view where country and state location is gathered looks like:
# _person_setup.html.erb
<td>
<%= f.label :country, 'Select your country' %>*<br />
<%= f.select :country, Carmen::country_names, {},
{:style => 'width: 200px',
:id => 'country_select',
:onchange => remote_function(
:url => {:action => 'update_states'},
:with => "'country='+value")} %>
</td><td>
<p>
<div id="states_div">
<%= render :partial => 'states',
:object => Carmen::states(
Carmen::country_code(
#person.country)),
:locals => {:form => f} %>
</div>
</p>
</td>
The partial being referenced in the DIV is as follows:
# _states.html.erb
<% unless states.nil? or states.empty? %>
<%= form.label :state, 'Select your state' %>*<br />
<%= form.select :state, states.collect{|s| [s[0], s[0]]} %>
<% else %>
<%= form.label :state, 'Please enter state or province' %>*<br />
<%= form.text_field :state %>
<% end %>
Finally, the controller code which is intended to update the list of states dynamically:
def update_states
puts "Attempting to update states..."
q = params[:country]
states = Carmen::states(Carmen::country_code(q))
puts "Country = #{q}, states = #{states.collect{|s| s[0]}.join(", ")}."
render :update do |page|
page.replace_html "states_div",
:partial => 'states',
:object => states,
:locals => {:form => form_for(#person)}
end
puts "OK"
end
Now, this code is being called at the proper time and generating the appropriate lists of states. For example, when the user clicks Australia, "Attempting to update states... Country = Australia, states = Australian Capital Territory, New South Wales, Northern Territory, Queensland, South Australia, Tasmania, Victoria, Western Australia" shows up in the server process. However it doesn't update the page, and won't print the "OK" at the end. In short the line which is failing is undoubtedly
page.replace_html "states_div",
:partial => 'states',
:object => states,
:locals => {:form => form_for(#person)}
Note that replacing this line with
page.replace_html 'states_div', "<b>is it working</b>"
properly replaces the div, but of course not with anything useful.
Can someone help me understand what is going on here?
It looks like you're assuming that the #person variable is still available from your original action. This could be set up by a filter for the current person but you don't show that in your question.
If you do need to lookup the #person again you'll have to pass the id through in your remote_function I think.
Ryan Bates has a Railscast that shows how to select a category for a product or create a new category by typing the name. It sounds like a similar scenario to what you have, so you might want to check it out: Create Model Through Text Field.
This took me a full day to figure out something that would at least "work". I am also using Carmen and also messing with the select tag in a form_for model form (actually, fields_for nested within forms_for...which adds additional complications).
I would think there is a better solution but this worked for me. The select needs to be referenced by the form but the options don't. Thus, first time through, I use the Carmen state_select method which populates the select tag correctly and all the nested options tags. The second time through, I just replace the options. Take a look:
In the view, I chose to use an observe_field method since I do other things besides update the states (some other localization changes) but this should work for remote_function and others, too:
<%= address_form.country_select :country, {:prompt => "--Select One--"} %>
Don't be confused by the id (user_address_attributes_country) it is just my silly forms_for/fields_for implementation)
<%= observe_field :user_address_attributes_country, :url => { :action => :changecountry }, :with => 'new_country' %>
<%= address_form.state_select :state, #user.address.country, {:prompt => "--Select One--"}, :style => 'width: 90px' %>
Then in my controller, it just looks like this:
def changecountry
c = params[:new_country]
respond_to do |format|
format.html
format.js {
render :update do |page|
page['user_address_attributes_state'].innerHTML = \
"<option>--Select One--</option>" + state_options_for_select(nil, c)
end
}
end
end
Note: state_options_for_select is also from Carmen. I could not get it to work unless I put it inside the respond_to block where I guess the view helpers are available. Also, I hard code user_address_attributes_state which is my nested id generated from the form_for/fields_for address_form.state_select rendering call in the view.
I hope this helps. If anyone can do it better, believe me, I'm all ears. I'll change the design in time...but needed something that just worked today and this was the best I could figure out in a limited time.

Populate form fields using a dropdown and AJAX with Rails

I have a form field where a user enters contact information, including name, email, etc. If they already have contacts saved I want to have a dropdown with their saved contacts. When a contact from the dropdown is selected, the contact fields should be populated with that data to allow for easy editing.
For some reason this approach isn't working:
In my new.html.erb view:
<%= f.collection_select :id, #contacts, :id, :name, :onchange =>
remote_function(:url =>{:action => 'populate_contact_form'}, :with => 'id') %>
In my controller:
def populate_contact_form
raise "I am working up to this point"
#contact = current_account.contacts.find(params[:id])
end
In populate_contact_form.rjs:
page['contact_name'].value = #contact.name
page['contact_email'].value = #contact.email
It seems my controller method is never called... can anyone explain how to do this?
It's not getting called because you're using remote_function incorrectly. Rails assumes the current action/controller/id/etc if any of those options are missing from the :url option to remote_function. You're passing :action as a top level option to remote_function, and it gets ignored. With a :url option Rails assumes the same action and controller that rendered this view.
This should fix your problem:
<%= f.collection_select :id, #contacts, :id, :name, :onchange =>
remote_function(:url =>{:action => 'populate_contact_form'}, :with => 'id') %>

Resources