2015-04-30 17 views
1

我正在構建rails應用程序我擁有屬於擁有多個教室的學校的用戶。如何將label_tag更改爲在rails應用程序中的下拉列表

用戶在關聯的教室中創建一個別針,並使用代碼確保他們將關聯關聯到正確的教室中。現在我有一個文本字段,但我需要切換到列出所有教室代碼的下拉菜單。我很難弄清楚這一點。 (新的RoR)。

這裏是形式的一部分,我需要改變形式創建針:

<div class="form-group"> 
    <%= label_tag(:classroom, "Enter your classroom code:") %> 
    <input type="text" name="pin[code]"> 
</div> 

課堂模式:

class Classroom < ActiveRecord::Base 

belongs_to :school 
belongs_to :teacher, :class_name => "User" 
has_and_belongs_to_many :users 

has_many :pins 
has_many :reflections 

validates_presence_of :school 
validates_presence_of :teacher 
validates :code, :uniqueness => { :scope => :school_id } 


end 

插針型

class Pin < ActiveRecord::Base 
belongs_to :user 
belongs_to :classroom 
has_and_belongs_to_many :emotions 

validates_presence_of :user 
validates_presence_of :classroom 

end 

引腳控制器

class PinsController < ApplicationController 
before_action :set_pin, only: [:show, :edit, :update, :destroy] 
respond_to :html 

def search 
    index 
    render :index 
    authorize @pins 
end 

def home 
@pins = Pin.all 
respond_with(@pins) 
authorize @pins 
end 

def show 
respond_with(@pin) 
end 

def new 
    @pin = Pin.new 
    @emotions = Emotion.all 
    @school = School.find(params[:school]) 
    respond_with(@pin) 
    authorize @pin 
end 

def edit 
end 

def create 
    code = params[:pin][:code] 
    @classroom = Classroom.where('code LIKE ?', code).first 
    unless @classroom 
    flash[:error] = "Classroom code incorrect" 
    render :new 
    else 
    params[:pin][:classroom_id] = @classroom.id 
    end 


    @pin = Pin.new(pin_params) 
    @pin.save 
    params[:pin][:emotion_ids].each do |emotion_id| 
    @emotion = Emotion.find(emotion_id) 
    @pin.emotions << @emotion 
    end 
    if @pin.save 
    redirect_to signout_path and return 
    end 
    respond_with(@pin) 
    authorize @pin 

end 

def update 
    @pin.update(pin_params) 
    respond_with(@pin) 
    authorize @pin 
end 

def destroy 
    @pin.destroy 
    respond_with(@pin) 
    authorize @pin 
end 
end 

回答

1

您可以使用select_tag助手在導軌中創建下拉選擇框。你可以做這樣的事情:

<div class="form-group"> 
    <%= label_tag(:classroom, "Select your classroom code:") %> 
    <%= select_tag "pin[code]", options_from_collection_for_select(Classroom.all, "code", "code") %> 
</div> 
+0

嘿,我得到這個昨天通過剛纔複製的工作和粘貼代碼,但由於某種原因,現在我得到一個錯誤說的代碼是空的,即使我已經選擇了它。有什麼建議麼? – user3787971

+0

@ user3787971很高興聽到它對您有用,對於您的第二個問題,我需要查看日誌以更好地瞭解正在發生的事情。 – Mandeep

+0

感謝您的回覆,我認爲我解決了它。在控制器創建方法中有點混亂。只需要一點重構。 – user3787971

相關問題