Rails中的静态嵌套元素

时间:2010-09-20 03:25:13

标签: ruby-on-rails nested-forms

我有一个“兴趣”列表,我系统中的每个用户都可以对其进行评分。管理员可以随时添加/删除兴趣。当用户去编辑他们的帐户时,我想显示系统中所有兴趣的列表,以及一个1..5值的下拉列表。我想知道我是如何设置它的。

使用accepts_nested_attributes似乎不起作用,因为当我使用field_for时,它想要为已保存的每个兴趣创建表单。我想要的是每个兴趣出现,并且在保存时,如果用户之前已经评价了兴趣,它会更新该值,如果之前没有被评级,则添加新条目。

目前是用户:

  has_many :user_interests, :dependent => :destroy
  has_many :interests, :through => :user_interests, :foreign_key => :user_id  

  accepts_nested_attributes_for :user_interests

目前是UserInterest:

  belongs_to :user
  belongs_to :interest

目前有兴趣:

  has_many :user_interests, :dependent => :destroy
  has_many :users, :through => :user_interests, :foreign_key => :interest_id, :dependent => :destroy

1 个答案:

答案 0 :(得分:0)

我最后只是翻转循环,所以首先循环利益,然后为每个循环创建表单元素。

<% Interest.all.group_by(&:interest_category).each do |category, interests| %>
    <p>
        <h4 id="interests"><%= category.title %></h4>
        <ul>
            <% interests.each do |interest| %>
            <% user_interest = @current_user.user_interests.find_by_interest_id(interest) || @current_user.user_interests.new(:interest_id => interest.id) %>
                <% form.fields_for "user_interests[#{interest.id}]", user_interest do |user_interests_form| %>
                    <li><%= user_interests_form.select :rating, options_for_select([1, 2, 3, 4, 5], user_interest.rating || ""), {:prompt => "-- Select One --"} %> <%= interest.title %></li>
                <% end %>
            <% end %>
        </ul>
    </p>
    <% end %>

在提交表单后为兴趣创建自定义setter。

  def user_interests=(interests)
    interests.each do |interest|
      interest_id = interest[0]
      rating = interest[1]["rating"]

      # confirm that a rating was selected
      if rating.to_i > 0
        # see if this user has rated this interest before
        int = self.user_interests.find_by_interest_id(interest_id)

        # if not, build a new user_interest for this interest
        int = self.user_interests.build(:interest_id => interest_id) if int.nil? 

        # set the rating
        int.rating = rating

        # save the new user_interest, or update the existing one
        int.save
      end
    end
  end