如何将嵌套表单的当前范围限制为第一项

时间:2013-07-23 02:43:12

标签: ruby-on-rails

我在Rails中创建了一个简单的讨论板。每个新Topic也会创建包含内容的第一个Reply。这是我目前的架构。

Topic
> title:string
> user_id: integer
has_many :replies
accepts_nested_attributes_for :replies

Reply
> topic_id: integer
> user_id: integer 
> content: text
belongs_to :topic

当前topics/_form.html.haml就是这样的

= form_for @topic fo |f|
  = f.text_field :title
  = f.fields_for :replies 
    = reply.text_area :content

问题是在尝试编辑主题时,我将所有回复列表视为可编辑,因为它在部分表单中迭代fields_for :replies字段。我应该只看到第一个。

将此迭代限制为当前第一个可用回复的方便方法是什么?如果主题是新的,还可以构建一个新的回复?

我最终得到了类似的东西,但是我认为应该有更好的方法。

# Topic model
has_one :owner_reply, class_name: 'Reply'
accepts_nested_attributes_for :owner_reply

# Form partial view
= form_for @topic fo |f|
  - reply_resource = (@topic.new_record? ? :replies : :owner_reply)
  = f.text_field :title
  = f.fields_for :replies 
    = reply.text_area :content

这些是完整的TopicsController#createupdate操作。

  def create
    @board = Board.find(params[:board_id])
    @topic = @board.topics.new(topic_params)
    @topic.user_id = current_user.id
    @topic.replies.each { |reply| reply.user_id = current_user.id }
    if @topic.save
      respond_to do |format|
        format.html { redirect_to topic_path(@topic) }
      end
    else
      render :new 
    end
  end

  def update
    @topic = Topic.find(params[:id])
    if @topic.update_attributes(topic_params)
      respond_to do |format|
        format.html { redirect_to topic_path(@topic) }
      end
    else
      render :edit
    end
  end

2 个答案:

答案 0 :(得分:1)

我会使用作用域关联,就像使用:owner_reply一样,但添加范围以限制第一条记录,如果需要,还可以为其添加order

class Topic
has_many :replies
has_many :first_replies, -> { first }, class_name: 'Reply'
accepts_nested_attributes_for :replies
accepts_nested_attributes_for :first_replies

在你看来

= form_for @topic fo |f|
  ...
  = f.fields_for :first_replies
    = reply.text_area :content

答案 1 :(得分:1)

Topic上创建一个返回第一个Reply

的类方法
class Topic
  accepts_nested_attributes_for :first_reply

  def self.first_reply
    self.replies.first
  end
  # ...
end

然后在fields_for中调用类方法。