Macoto
Macoto

Reputation: 63

convert string in a field name 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.

Upvotes: 2

Views: 2596

Answers (2)

Shiv
Shiv

Reputation: 8412

I think I understood your question. You will need to use the send function

<%= price.send("list_#{current_user.price}".to_sym) %>

Upvotes: 5

Kyle Macey
Kyle Macey

Reputation: 8154

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

Upvotes: 1

Related Questions