2014-06-20 4 views
3

Ruby on Rails 4.1양식의 임시 속성을 만들고 사용하십시오.

양식에 테이블 열 이름을 선택할 수있는 옵션이 있습니다. 폼에서 선택한 테이블 열에 텍스트를 입력하고 싶습니다. 이렇게하려면 임시 애트리뷰트를 만들어 폼이 값을 저장하고 create 메소드에서 검사 할 수 있도록하려고합니다. 그런 다음 올바른 열에 텍스트를 지정한 다음 저장하십시오.

컨트롤러 :

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 do |format| 
    if @word.save 
     format.html { redirect_to @word, notice: 'Word was successfully 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 

양식은 :

<%= simple_form_for(@word) do |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 %> 

이다 오류 내가 얻을 : 양식의 언어 속성이 없기 때문에입니다

undefined method `language' for #<Word:0x007f6116b1bcb8> 

용도. 그래서 컨트롤러 new()에서 임시 코드를 만들려고했습니다.

이 작업을 수행 할 수있는 방법이 있습니까? 또는 양식에서 참조 할 데이터베이스 테이블의 언어 및 번역을 작성해야합니까?

+0

사용 간단 :이 양식을 제출하면

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

것은, 그것은 당신에게 편집 할 column_name 속성을 줄 것이다 그 값에 대한 도우미를 입력하십시오. 'text_field' 또는'select'와 같습니다. – zishe

+0

또한'create''@ language'와'@ translation' 메서드는 정의되어 있지 않습니다. – zishe

답변

4

가상 특성

당신 수도가 "진짜"와 동일하게 작동 모델의 속성을 가상 속성를 생성

모델에 attr_accessor를 사용 혜택 :

#app/models/word.rb 
Class Word < ActiveRecord::Base 
    attr_accessor :column_name 
end 

이렇게하면이 attr에 값을 할당 할 수 있습니다. 당신이 원하는 것처럼 소리 DB에 저장되지 않습니다 ibute :

#app/controllers/words_controller.rb 
Class WordsController < ApplicationController 
    def create 
     # ... you'll have "column_name" attribute available 
    end 
end 
+1

흥미 롭군요, 네, 이것이 제가 원하는 것입니다. 나는 대답으로 받아들이 기 전에 이것을 먼저 할 것이다. +1 – DDDD

관련 문제