0

Perhaps I'm being silly but I've been trying to set a default value for an input with ruby on rails for hours and haven't cracked it.

I'm making a partial which can either allow users to create new records but will also show existing records if they exist. Code as follows

<input type="text" <%= (@prices.empty? || @prices.first.name.length == 0) ? 'placeholder="General admission"' : "value=" + @prices.first.name.to_s %> >

Which works perfectly for any value that exists UNLESS there is a space, for example, if price.name = "general admission" OR if price.name = "" (in which case it prints the placeholder) I get the following produced

<input type="text" admission&#39;="" value="'general" id="event_price_name" name="[event][price][0][name]" aria-label="..." class="form-control">

It seems to get tripped up by the space.

Am I trying to use Rails in a way it wasn't designed to be done in? I'm more used to PHP which may be it!

Thanks

1 Answer 1

2

You should use the text_field_tag helper to build the input, this is preferred over building it with partial interpolation. Also, placeholder will automatically be overwritten if there is a value so you don't need to handle that part in the code, that's how it behaves by default on the browser.

<%= text_field_tag :admission, @prices.first.name.to_s, {placeholder: 'General Admission'} %>
Sign up to request clarification or add additional context in comments.

1 Comment

Additionally, if you want a default value you normally set that up in the controller. Your input fields are typically based on columns in the database (or "attributes on the model" if you prefer) and as such you instantiate an object and give it some default values. The main takeaway is this: you cannot code PHP-style in Ruby or RoR. It will not work. My advice to you is what I give everybody in your position: stop - literally stop - and read the Rails book cover to cover. You can do it in a few days but you'll end up way ahead in a week.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.