[英]rails 3 query string params
I try to make a simple message controller with new/create actions, when I call new action I give through query string the to_id param, 我尝试使用new / create动作制作一个简单的消息控制器,当我调用通过查询字符串给to_id参数的new动作时,
/messages/new?to_id=1 / messages / new?to_id = 1
that contains id of recipient, now my code is: 包含收件人的ID,现在我的代码是:
def new
@message = Message.new
@message.to = User.find(params[:to_id])
end
def create
@message = Message.new(params[:message])
@message.from = current_user
respond_to do |format|
if @message.save
format.html { redirect_to messages_path }
else
format.html { redirect_to common_error_path, :notice => "failed to send message" }
end
end
end
It's pretty default, my problem is that the changes in @message object that have been made in new action are not available in create action and I lose my to_id value, the first thing come to my mind is to store to_id value using session object, but I think it's not the best idea, maybe someone have better solution for this 这是非常默认的设置,我的问题是,在new动作中对@message对象所做的更改在create动作中不可用,并且我失去了to_id值,我首先想到的是使用会话对象存储to_id值,但我认为这不是最好的主意,也许有人对此有更好的解决方案
You'll need to pass that parameter back with the POST
on create. 您需要在创建时通过POST
将该参数传递回来。 For example, if you have a 例如,如果您有一个
belongs_to :to, :class_name => 'User'
association on your Message
model, you could do 您的Message
模型上的关联,您可以
app/views/messages/new.html.erb
<%= form_for @message do |f| %>
<%= f.hidden_field :to_id %>
...
<% end %>
The above assumes you've kept your new
action the same. 以上假设您将new
操作保持不变。 Now, on your create
action, your params[:message]
would be equal to {:to_id => 1}
and would assign it properly. 现在,在您的create
动作中,您的params[:message]
等于{:to_id => 1}
并将正确分配。
Does that make sense? 那有意义吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.