如何将参数从form_for传递到另一个控制器?

时间:2011-11-24 19:15:32

标签: ruby-on-rails

我有一个问题模型和一个评论模型。关于#show view的问题,我有一个评论表。我在问题#show controller action中为表单创建@comment,然后将其传递给注释#create controller action以实际创建并将注释保存到db。但是,一旦@comment参数传递给注释#create action,我就不再拥有我需要的issue_id信息。我如何传递这些信息?这是我的文件:

<%= form_for @comment do |f| %>
    <%= render 'comment_fields', :f => f %>
    <%= f.submit "Submit" %>
<% end %>

问题控制器:

  def show
     @issue = Issue.find(params[:id])
     @votes = Votership.where(:issue_id => @issue.id)
     @current_user_vote = @votes.where(:user_id => current_user.id).first
     @comment = Comment.new
  end

和评论控制器:

  def create
    @comment = Comment.new(params[:comment])
    @comment.save
    redirect_to :back
  end

2 个答案:

答案 0 :(得分:0)

您只需要在@comment操作中修改show的创建方式

def show
  @issue = Issue.find(params[:id])
  @votes = Votership.where(:issue_id => @issue.id)
  @current_user_vote = @votes.where(:user_id => current_user.id).first
  @comment = @issue.comments.build # assigns issue_id to comment
end

现在,当您为@comment呈现表单时,issue_id应该出现在隐藏表单输入中


这与您的问题无关,但我也注意到您加载的方式@current_user_vote

@current_user_vote = @votes.where(:user_id => current_user.id).first

你应该这样做:

@current_user_vote = current_user.votes.first

答案 1 :(得分:0)

如果我理解得很清楚,问题可能会有很多评论,评论属于某个问题吗?

# config/routes.rb
# Nest the comment under the issue
resources :issues do
  resources :comments, only[:create]
end

# app/models/issue.rb
has_many :comments

# app/models/comment.rb
belongs_to :issue

# app/controllers/issues_controller.rb
def show
  @issue = Issue.find params[:id]
  ...
end

# app/views/issues/show.html.erb
<%= form_for [@issue, @issue.comments.build] do |f| %>
....
<% end %>

# app/controllers/comments_controller.rb
def create
  @issue = Issue.find params[:issue_id]
  @comment = @issue.comments.build params[:comment]
  if @comment.save
    redirect_to @issue
  else
    render 'issues/show' # => it will know which issue you are talking about, don't worry
  end
end

# or if you don't need validation on comment:
def create
  @issue = Issue.find params[:issue_id]
  @issue.comments.create params[:comment]
  redirect_to @issue
end

问题#显示有点看起来很奇怪。

def show
  @issue = Issue.find params[:id]
  @votes = @issue.voterships
  @current_user_vote = current_user.votes.first
  # maybe you want to list all the comments: @comments = @issue.comments
end