2013-07-17 58 views
0

從窗體獲取值到控制器時出現問題。我正在使用rails 4.0。導軌從查看到控制器獲取值

我的看法是這樣的(new.html.erb)

<h1> POST A NEW LISTING </h> 

    <% if current_user.nil? %> 
     <h2>You must be logged in to view this page </h2> 
    <% else %> 
     <%= form_for [@user, @listing] do |f| %> 
     <%= f.label :title, 'Title' %> <br /> 
     <%= f.text_field :title %> 

     <%= f.label :general_info, 'General Information' %> <br /> 
     <%= f.text_area :general_info %> 

     <%= f.label :included, 'Included' %> <br /> 
     <%= f.text_field :included %> 

     <%= f.label :length, 'Length' %> <br /> 
     <%= f.text_field :length %> 

     <%= f.label :price, 'Price' %> <br /> 
     <%= f.text_field :price %> 

     <%= fields_for @tagging do |u| %> 
     <%= u.label :tag, 'Tag' %> <br /> 
     <%= u.text_field :tag %> 
     <% end %> 

     <%= f.submit "submit" %> 
    <% end %> 

    <% end %> 

我想添加標籤。我有2個模型來處理標籤:

車型 - > tag.rb

class Tag < ActiveRecord::Base 
    has_many :taggings 
    has_many :listings, through: :taggings 
end 

車型 - > tagging.rb

class Tagging < ActiveRecord::Base 
    belongs_to :tag 
    belongs_to :listing 
end 

標籤跟蹤標籤名稱本身,而引用的Tagging跟蹤與列表的連接。

當用戶提交表單時,他們將輸入字符串標籤,如「exampletag」。然後我需要搜索我的標籤模型以獲取特定標籤的tag_id。如果存在,我需要將tag_id和listing_id放入標記中。目前,我有正確的listing_id,但即使從表單中訪問:標記符號,也有問題。

這是我到目前爲止。目前還不是:tag_id是硬編碼的,因爲我不能獲得@current_tag來返回我需要的信息。

listings_conroller.rb#創建

def create 
    @user = User.find(current_user.id) 
    @listing = @user.listings.build(listing_params)  
    #save before we get the listing ID 

    if @listing.save 

     @current_tag = Tag.where(:name => params[:tag]) 
      @taggings = Tagging.new(:tag_id => 1, :listing_id => @listing.id) 

     if @taggings.save 
      flash[:success] = "Success" 
      redirect_to root_path 
     else 
      render :action => 'new' 
     end 
    else 
    render :action => 'new' 
    end 

    end 

我認爲@current_tag = Tag.where(:名稱=> PARAMS [:標籤])將返回正確的上市,但它似乎是返回null當我用數據庫中的名字提交表單。

回答

1

明白了!

由於標籤是根據嵌套的Tagging我需要訪問PARAM爲:的

params[:tagging][:tag] 

代替PARAMS [:標籤]