【问题标题】:Pass view from controller, to view, and back to controller in Rails 4.0在 Rails 4.0 中将视图从控制器传递到视图并返回到控制器
【发布时间】:2014-01-17 17:29:43
【问题描述】:

我的控制器方法中有以下内容:

@comment = Comment.where(:reviewed_at == nil).first

那么,在我看来,我有这个:

<b><%= @comment.comment %></b>
<br>
<br>

<%= simple_form_for :phrase do |f| %>
    <%= f.input :phrase, label: 'Phrase you would like to add:' %>
    <br>
    <%= f.input :emotion, collection: [[true, 'Positive'], [false, 'Negative']], as: :radio_buttons, label: 'Emotion', label_method: :last %>
    <br>
    <%= f.input :category, collection: @categories, as: :radio_buttons, label: 'Categories', label_method: :last %>
    <br>
    <%= f.button :submit, 'Add to Dictionary' %>
<% end %>

当按下:submit 按钮时,我还需要将@comment 传递回我的控制器,或者以某种方式从我的控制器访问@comment。我尝试使用-

f.hidden :comment, :value =&gt; @comment

在我的simple_form_for block 内,但没有骰子。我知道我可以通过查询数据库再次查看评论,但我觉得这不是正确的方法。如何将我的变量传递给视图,然后再传回控制器?

【问题讨论】:

    标签: ruby-on-rails view controller


    【解决方案1】:

    您无法在hidden_field 中传输对象,但可以通过将其添加到表单中来传输 id

    f.hidden_field :comment_id, :value => @comment.id
    

    因此,在接收控制器操作中,您可以通过以下行访问注释

    @comment = Comment.find(params[:phrase][:comment_id])
    

    这应该为你做,...它是查询数据库然后将对象从一个操作传递到另一个操作的更好方法,因为当您在数据库中进行更改但使用过时的对象并保存时,这可能会导致可怕的问题或编辑此对象并将其写回数据库。

    【讨论】:

    • 谢谢,这很有道理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    相关资源
    最近更新 更多