我有三个模型:Post,
Reply
和Vote
。作为与andVote
的多态关联:Post
Reply
路线.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 的帖子表单。这很难,因为两者posts
都replies
在同一个显示视图中。
有什么解决方法吗?(或者有更好的方法吗?比如让@votable
投票控制器中的变量在后控制器中可用?)