1

我有三个模型:Post, ReplyVote。作为与andVote的多态关联:PostReply

路线.rb:

   resources :posts do
    resources :votes
    resources :replies do
      resources :votes
    end
  end
  resources :votes,         only: [:create, :destroy]

votes_controller.rb:

  def create
    @votable = find_votable
    @vote = @votable.votes.create(params[:vote])
    if @votable.save
     # vote saved
    else
      render :action => 'new'
    end
  end

  private

  def find_votable
    params.each do |name, value|
      if name =~ /(.+)_id$/
        return $1.classify.constantize.find(value)
      end
    end
    nil
  end

post_controller.rb:

def show
    @post = Post.find(params[:id])
    @replies = @post.replies.paginate(page: params[:page])
    @reply = @post.replies.build
    @votable = ? # not sure what to add here
    @vote = Vote.new
 end

帖子/show.erb:

  <%= form_for ([@votable, @vote]) do |f| %>
    <p>
      <%= f.label :polarity %><br />
      <%= f.text_field :polarity %>
      <%= f.label :user_id %><br />
      <%= f.text_field :user_id %>
    </p>
    <p><%= f.submit "Submit" %></p>
  <% end %>

  <%= render 'replies/form' %>

回复/form.rb:

  <%= form_for ([@votable, @vote]) do |f| %>
    <p>
      <%= f.label :polarity %><br />
      <%= f.text_field :polarity %>
      <%= f.label :user_id %><br />
      <%= f.text_field :user_id %>
    </p>
    <p><%= f.submit "Submit" %></p>
  <% end %>

我不确定如何@votable在 post 控制器中定义,所以它Post.find(params[:id])适用于 post 的投票表单和Reply.find(params[:id])vote 的帖子表单。这很难,因为两者postsreplies在同一个显示视图中。

有什么解决方法吗?(或者有更好的方法吗?比如让@votable投票控制器中的变量在后控制器中可用?)

4

1 回答 1

0

您尝试的内容称为嵌套表单。多态的关系不应该影响如何实现它。试试看下面的 railscast

http://railscasts.com/episodes/196-nested-model-form-part-1

并检查这颗宝石

https://github.com/ryanb/nested_form

它很旧,因此可能会有更新的宝石和方法。

于 2012-11-19T05:58:07.487 回答