mr_muscle
mr_muscle

Reputation: 2900

Rails 6 pass variable to partial

I want to render a partial for each conversation. I have the following code:

# app/views/messages/_new.html.erb
<%= simple_form_for [@conversation, @message] do |f| %>
  <%= f.text_area :body %>
  <%= f.text_field :messageable_id, value: current_user.id, type: "hidden" %>
  <%= f.text_field :messageable_type, value: "#{current_admin_user.class.name}", type: "hidden" %>
  <%= f.submit "Send Reply" %>
<% end %>

I want to change value of both hidden text fields depends on passed variable. Something like:

# app/views/admin/conversations/_show.html.erb
<%= render 'messages/new', value: current_admin_user.id %>

With below code I'm getting an error Validation failed: Messageable must exist which means messageable_id = nil

Upvotes: 2

Views: 2238

Answers (1)

Deepak Mahakale
Deepak Mahakale

Reputation: 23661

Because you are not using the value you are passing to the partial.

Also, you need to pass both the variables

Try replacing the partial with the following

# app/views/admin/conversations/_show.html.erb
<%= render 'messages/new', messageable_id: current_admin_user.id, messageable_type: "#{current_admin_user.class.name}" %>

and use them

# app/views/messages/_new.html.erb
<%= simple_form_for [@conversation, @message] do |f| %>
  <%= f.text_area :body %>
  <%= f.text_field :messageable_id, value: messageable_id, type: "hidden" %>
  <%= f.text_field :messageable_type, value: messageable_type, type: "hidden" %>
  <%= f.submit "Send Reply" %>
<% end %>

NOTE: If you want the _new partial to render on its own as well

replace it with something like this:

<% messageable_id ||= current_admin_user.id %>
<% messageable_type ||= "#{current_admin_user.class.name}" %>
<%= f.text_field :messageable_id, value: messageable_id, type: "hidden" %>
...

Upvotes: 4

Related Questions