2011-11-24 127 views
1

我有一个问题模型和一个评论模型。在问题#show view中,我有一个评论表单。我在问题#show controller动作中为表单创建了@comment,然后将它传递给注释#create controller action以实际创建并将注释保存到数据库。但是,一旦@comment参数传递给comment#create动作,我不再拥有需要的issue_id信息。我将如何传递这些信息?下面是我的文件:如何将参数从form_for传递到其他控制器?

<%= 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 

回答

0

你只需要修改你的show行动

创建 @comment方式
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 

现在,当您呈现形式@commentissue_id应该是存在于隐藏的表单输入


这无关你的问题,但我也注意到你正在加载@current_user_vote

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

你或许应该这样做,因为:

@current_user_vote = current_user.votes.first 
+0

我通过创建问题#show view的注释来尝试这样的事情,它包含我需要的正确变量。然而,当它传递给注释#create操作时,当我做了Comment.new(params [:comment])它删除了该变量(我相信因为它创建了一个新的注释并且在params中没有包含该变量[ :评论])。当我尝试你的代码时,build_comment给了我一个错误:未定义的方法'build_comment' –

+0

您使用的是哪个版本的Rails?我更新了我的答案。 –

+0

版本3.1 ...我需要的是一种将issue_id传递给我的评论控制器的方法。我几乎通过传递隐藏字段来实现它的工作,就像这样:<%= hidden_​​field(:issue_id,@ issue.id)%>然而,我不认为我实现了这个权利,因为它传递了一个叫做issue_id key = @ issue.id和value = nil。 –

0

如果我没理解好,一n问题可能有很多评论和评论属于一个问题?

# 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 
+0

是的,但我没有注释资源......这是不需要的。这不起作用 –

+0

我加入了一个资源。但是,评论属于应用程序的问题。所以有一个双重嵌套的资源。在那种情况下我会怎么做? –

+0

但我如何使用您建议的其他代码知道我需要app/issue/comment –

相关问题