I am new to rails and I am having a hard time assigning the foreign key user_id
to user_profile
.
When a user creates an account it is saved to the database, then they are taken to create a profile. The user can create the profile and the profile is saved to the database. I used to have
<tr>
<th><%= f.label(:user_id, "User ID") %></th>
<td><%= f.text_field(:user_id) %></td>
</tr>
assign on the user profile form, and it worked, user.user_profile showed there was a relationship. but I don't want a user to have to/be able to choose the user_id they are creating a profile for. I can't figure out how to assign the user_id to the user_profile. in the controller for user_profiles I have
def new
@user = User.find(session[:user_id])
@user_profile = UserProfile.new({:user_id => @user.id})
end
and for the new page for user_profiles I have
<%= form_for(:user_profiles, :url => {:action => 'create', :user_id => @user.id}) do |f| %>
<%= render(:partial => "form", :locals => {:f => f}) %>
<% end %>
any ideas? Thank You
Assuming you are on rails 4, you just need to add into User.rb
has_many :user_profiles, dependent: :destroy
and into user_profile.rb
belongs_to :user
validates :user_id, presence: true
user_profiles_controller.rb
def create
@user_profile = current_user.user_profiles.build(user_profile_params)
....
end
private
def user_profile_params
params.require(:user_profile).permit(:param1, :param2)
end
form view
<%= form_for(@user_profile) do |f| %>
<%= render(:partial => "form", :locals => {:f => f}) %>
<% end %>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.