How do I pass values that aren't part of the Model through a form in Rails?
I have a form used for creating a new record of the model Message.
However, the route to create this has been customized to look like:
match 'messages/:sender_id/to/:receiver_id' => "messages#new", :as => :send_message
I want from the new action to then pass the values for :sender_id and :receiver_id so I can I assign it to a related model, called UserHasMessages.
This model needs to be created whenever a new record for Message is created.
But I can't use hidden fields because :sender_id is NOT an attribute of Message. it is an attribute of UserHasMessages.
Thanks.
controller/messages_controller.rb
def create
15 @message = Message.new(params[:message])
16 if @message.save
17 @user_has_message = UserHasMessages.new
18 @user_has_message.user_id = params[:sender_id]
19 @user_has_message.message_id = @message.id
20 @user_has_message.开发者_如何学Gois_sender = 1
21 @user_has_message.save
22
23 @user_has_message = UserHasMessages.new
24 @user_has_message.user_id = params[:receiver_id]
25 @user_has_message.message_id = @message.id
26 @user_has_message.is_sender = 0
27 @user_has_message.save
view/messages/_form.
<%= form_for @message do |f| %>
2 <%= f.error_messages %>
3 <p>
4 <%= f.label :subject %><br />
5 <%= f.text_field :subject %>
6 </p>
7 <p>
8 <%= f.label :body %><br />
9 <%= f.text_area :body %>
10 </p>
11 <p>
12 <%= f.label :contact_id %><br />
13 <%= f.text_field :contact_id %>
14 </p>
15 <p>
16 <%= f.label :company_id %><br />
17 <%= f.text_field :company_id %>
18 </p>
19 <p>
20
21 <%= hidden_field_tag :sender_id, :value => params[:sender_id] %>
22 <%= hidden_field_tag :receiver_id, :value => params[:receiver_id] %>
23 </p>
24
25 <p><%= f.submit %></p>
26 <% end %>
message_controller/new
10 def new
11 @message = Message.new
12 end
In the form_for, it is possible to pass stand alone values not related to the model object like this
form_for :message do |f|
f.text_field ..
...
hidden_field_tag :sender_id, params[:sender_id]
hidden_field_tag :receiver_id, params[:receiver_id]
end
These can be accessed in create
method as params[:sender_id]
and params[:receiver_id]
i'm not sure i understand your question... Let's try according to what i understand so far :)
i believe whatever parameter you put in a form field will be accessible in the params hash of your controller. For instance, if you put a form field named 'test_field', then in your controller you'll be able to read it's value via params[:test_field].
In your controller, i recommend you put a line like this while testing: puts params.inspect
Hope that helps! Pierre.
精彩评论