【问题标题】:How do I retrieve the values of a link in Ruby on Rails如何在 Ruby on Rails 中检索链接的值
【发布时间】:2019-05-11 20:20:49
【问题描述】:

在 PHP 中,要在 PHP 中检索链接的值,我所要做的就是使用 $_GET['value']

现在在 Ruby on Rails 中,我该怎么做?例如,假设我有这个链接,我想检索它的 id 并在表单中使用它。

这是链接

<%= link_to "Message", new_message_path %># This link will allow the viewer to message the profile owner

这是消息脚本

<%= form_for(@message) do |f| %>

  <%= render 'shared/error_messages', object: @message %>

  <%= f.label :content %>
  <%= f.hidden_field :receiver, value:# The ID should be retrieved from the user id of the previous page %>
  <%= f.text_area :content, size:"20x15" %>
  <%= f.submit "Send message", class: "btn btn-primary" %>
  <% end %>

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-5


    【解决方案1】:

    我怀疑您可能在谈论查询参数(例如/new?receiver_id=1234 上的receiver_id)。您也可以在 Rails 上执行此操作,方法是将其他参数传递给用于路由的辅助函数,例如:

    <%= link_to "Message", new_message_path(receiver_id: @receiver.id) %>
    

    这会产生类似/messages/new?receiver_id=1 之类的东西。

    然后您可以在控制器中使用params 变量来访问查询参数,例如params[:receiver_id],在这种情况下会产生1

    【讨论】:

    • 不会和rails的>create方法冲突吗?这将创建与登录用户关联的消息/帖子,例如 @message = current_user.messages.build
    猜你喜欢
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    相关资源
    最近更新 更多