Home>
I want to achieve

I want to register data in the friends table. (Follow function)

Current status

users↔︎friends↔︎farmers
So, users and farmers are N vs. N.

Error location
ActiveRecord :: AssociationTypeMismatch in FriendsController # create
User (# 70277525473660) expected, got "2" which is an instance of String (# 70277522570720)
class FriendsController</pre>
<p><br />
The error statement is useless because the parameter that I got for the foreign key of User is String! I interpret it as being angry, but what I sent from view was<code>value: current_user</code>Isn't it a number? ?? I am worried.</p>
<strong>Corresponding code</strong>
<pre><code>At the stage of populars, it is in the order of sales, but after that, it is just in the order of product id. .. ..
(Show.html.erb)
                                
                                  <% = form_for (Friend.new, url: friends_path, html: {class: "follow_farmer"}) do | f |%>
                                      <% = f.hidden_field: user, value: current_user.id%>
                                      <% = f.hidden_field: farmer, value: params [: id]%>
                                      <% = f.submit "follow", class: "follow_btn"%>
                                  <% end%>
                              
(Friends_controller.rb)
class FriendsController</pre>
<pre><code>model:
farmer.rb
has_many: friends, dependent:: destroy
model:
friend.rb
class Friend</pre>
<pre><code>model:
user.rb
has_many: friends, dependent:: destroy
Friends table
class CreateFriends
  • Answer # 1

    <% = f.hidden_field: user, value: current_user.id%>
    <% = f.hidden_field: farmer, value: params [: id]%>


    The column name is user/farmer in, but since it is user_id/farmer_id in the friends table in the first place, ...

    <% = f.hidden_field: user_id, value: current_user.id%>
    <% = f.hidden_field: farmer_id, value: params [: id]%>


    It should be.
    Therefore, you should change the strong parameters as well.

  • Answer # 2

    Different from the answer,
    Malicious userparams.user (user_id)If you modify the value of
    Would you like to let any user follow you?

    user (user_id)The value of is not embedded in the form
    Of the controllercurrent_user.idI think it's better to bring it from

Related articles