2012-03-20 18 views
0

私はこのコード行を持っているレールのテーブルに参加しましたselect_tagselect_tagにアルファベット順に発注、

Friendshipsにはfriendsテーブルにリンクするfriendship_idがあります。私は、Webページ上の名前のリストを参照してください原因の関連作品

友情コントローラで

def name 
    self.friend.name 
end 

を使用して名前を呼びます。

私はしたいと思います:アルファベット順

  • がリスト
  • の上部にある「...友人を選択し、」追加して、私は本当に発見していないことを

    1. 順序をまだ何か。 問題2の場合は、selected = nilを無駄に追加します。あなたの助けを事前に

      おかげ

      EDIT(ANSWER):

      私は、コレクションがフェッチされた道をchaging終わった、と友人の代わりに、友情を探しました。

      <%= select_tag :friend_id, options_from_collection_for_select(current_user.friends, "id", "name"), :prompt => 'Select a friend...', :id => 'thought_contact_select' %> 
      
      私のUserモデルで

      has_many :friends, :through => :friendships, :order => :name 
      

      私はちょうどその友人のために関連した友情とコントローラ

      friendship = Friendship.find_by_user_id_and_friend_id(current_user.id, params[:friend_id])  
      

    答えて

    0
    1. 使用default_scopeに、そのユーザーを探しザ・:名前が、使用一度! 1つのデフォルトスコープが必要です。ここhas_manyのか、あなたはhas_manyアソシエーション使用して友情をアクセスしているようhas_many :friendships, :order => 'name DESC'の説明を参照してください:http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-select_tag

    EDIT:

    を私はあなたを理解している場合select_tagから:promptオプション、参照http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

  • 使用

    class User < ActiveRecord::Base 
        has_many :friendships 
        has_many :friends, :through => :friendships 
    end 
    
    class Friendship < ActiveRecord::Base 
        belongs_to :user 
        belongs_to :friend 
    end 
    
    class Friend < ActiveRecord::Base 
        has_many :friendships 
        has_many :users, :through => :friendships 
    end 
    

    Userクラスを次のように変更してください。

    class User < ActiveRecord::Base 
        has_many :friendships 
        has_many :friends, :through => :friendships, :order => 'name' 
    end 
    
  • +0

    番号2の問題を解決しました。しかし、Number 1の問題は機能しません。なぜなら、current_user.friendshipsを呼び出していて、名前がfriendsという3番目のテーブルにあるからです。エラー 'SQLite3 :: SQLException:no such column:name:SELECT" * FROM "friendships" where "friendships"。 "user_id" = 6 ORDER BY name DESC' – wachichornia

    +0

    改訂の答えを確認してください。 – wrzasa

    関連する問題