【问题标题】:ordering alphabetically in a select_tag, joined table in rails在 select_tag 中按字母顺序排序,在 rails 中连接表
【发布时间】:2012-03-20 21:22:01
【问题描述】:

我有这行代码:

 <%= select_tag :friendship_id, options_from_collection_for_select(current_user.friendships, "id", "name", selected = nil) %>

在“朋友”表中选择记录的“名称”并将其作为选项放在 select_tag 上

Friendships 有一个friendship_id 链接到friends 表。我用

来称呼这个名字
def name
  self.friend.name
end

在友谊控制器中

该关联有效,因为我在网页上看到了姓名列表。

我想:

  1. 按字母顺序排列
  2. 在列表顶部添加“选择朋友...”

我还没有真正找到任何东西。 对于问题 2,我添加 selected = nil 无济于事。

提前感谢您的帮助

编辑(回答):

我最终改变了收集收藏的方式,并寻找朋友而不是友谊。

 <%= select_tag :friend_id, options_from_collection_for_select(current_user.friends, "id", "name"), :prompt => 'Select a friend...', :id => 'thought_contact_select' %>

在我的用户模型中

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

我只是在控制器上查找与该朋友和该用户关联的友谊

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

【问题讨论】:

    标签: ruby-on-rails forms activerecord html-select


    【解决方案1】:
    1. 使用 default_scope :name 但只使用一次!您应该有一个默认范围。或者,当您通过has_many 关联使用has_many :friendships, :order =&gt; 'name DESC' 访问友谊时,请在此处查看has_many 的描述:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
    2. :prompt 选项用于select_tag,参见:http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-select_tag

    编辑:

    如果我理解你,你应该:

    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
    

    【讨论】:

    • 第二个问题解决了!。但是,第 1 个问题不起作用,因为我正在调用 current_user.friendships,并且名称在名为 Friends 的第三个表中,所以它给了我错误 SQLite3::SQLException: no such column: name: SELECT "friendships".* FROM "friendships" WHERE "friendships"."user_id" = 6 ORDER BY name DESC
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多