Saturday, 15 February 2014

ruby on rails - Make and use temporary attribute for a form -



ruby on rails - Make and use temporary attribute for a form -

ruby on rails 4.1

the form has alternative select table column name. want input text table column selected form. trying create temporary attributes form can utilize store value , examine in create method. assign text right column, save.

controller:

def new @word = word.new @language = word.new(params[:language]) @translation = word.new(params[:translation]) @language_options = word.column_names end def create @word = word.new(word_params) if @language == "arabic" @word.arabic == @translation end respond_to |format| if @word.save format.html { redirect_to @word, notice: 'word created.' } format.json { render :show, status: :created, location: @word } else format.html { render :new } format.json { render json: @word.errors, status: :unprocessable_entity } end end end

the form:

<%= simple_form_for(@word) |f| %> <%= f.error_notification %> <div class="form-inputs"> <%= f.input :name, placeholder: 'english string' %> <%= f.input :language, collection: @language_options %> <%= f.input :translation, placeholder: 'translated string' %> </div> <div class="form-actions"> <%= f.button :submit %> </div> <% end %>

this error get:

undefined method `language' #<word:0x007f6116b1bcb8>

which because there not language attribute form use. trying create temporary 1 in controller new().

is there way or have create :language , :translation in database table reference in form?

virtual attribute

you may benefit using attr_accessor in model

this creates virtual attribute works same "real" attributes in model:

#app/models/word.rb class word < activerecord::base attr_accessor :column_name end

this allow assign values attribute won't saved db, sounds want:

#app/views/words/new.html.erb <%= simple_form_for(@word) |f| %> <%= f.input :column_name %> <%= f.select :column_name, @language_options %> <% end %> <% end %>

when submit form, give column_name attribute edit:

#app/controllers/words_controller.rb class wordscontroller < applicationcontroller def create # ... you'll have "column_name" attribute available end end

ruby-on-rails ruby forms ruby-on-rails-4

No comments:

Post a Comment