Search code examples
ruby-on-rails-4belongs-to

Accessing and editing associated data in rails


I have two tables one called events and the other sessions. There can be multiple events with the same session_name but each event will only have one session_name

enter image description here

class Session < ApplicationRecord
  belongs_to :event, foreign_key: 'session_id'
end
class Event < ApplicationRecord
  has_one :session
end

I am not entirely sure how to set up belongs_to and has_one. i've tried looking at tutorials and other examples but they are all a little different then what i have.

In the form_for events how can i get it where it finds or creates a new session_name and session_id gets the right id

In my controller I tried this for my edit form but this only displays the id of the event and not up the session

 def edit
   @events = Event.find(params[:format])
   @session = @events.session.id
 end

I know this is a lot any help or directions will be much appropriated, i've been tried to wrap my head around this i'm not the greatest when it comes to databases and activerecord. I appreciated any criticism just don't be a jerk about it.

UPDATE

I got the edit and new form to show but how do i save/update it to the database. Here is my form. The only field in the sessions table the user will fill out is the session_name. When they hit save/update i need the events table to find or create the sessions.id and insert that into events.session_id.

<%= form_for @session,html:{ class:'form-horizontal', style:'color:white;margin:auto;'}, url: signup_path do |s| %>
  <%= s.fields_for :event do |e| %>

    <label class="col-form-label">Event:</label>
    <%= e.select(:eventname, [['Pink Ribbon Invite'],['2018 Missouri State Championship - KC']],{ :include_blank => false }, class: 'form-control')%>

      <label class="col-form-label">First Name:</label>
      <%= e.text_field(:firstname, class: 'form-control') %>
        <label class="col-form-label">Last Name: </label>
        <%= e.text_field(:lastname, class: 'form-control') %>

          <label class="col-form-label">Phone Number: </label>
          <%= e.telephone_field(:phone, class: 'form-control') %>
            <label class="col-form-label">Email: </label>
            <%= e.email_field(:email, class: 'form-control') %>

              <label class="col-form-label">Street Address:</label>
              <%= e.text_field(:streetaddress1, class: 'form-control') %>

                <label class="col-form-label">Street Address 2: </label>
                <%= e.text_field(:streetaddress2, class: 'form-control') %>

                  <label class="col-form-label">City:</label>
                  <%= e.text_field(:city, class: 'form-control') %>

                    <label class="col-form-label">State: </label>
                    <%= e.text_field(:state, class: 'form-control') %>

                      <label class="col-form-label">Zip:</label>
                      <%= e.text_field(:zip, class: 'form-control') %>

                        <label class="col-form-label">Gymnast</label>
                        <%= e.text_field(:gymnast, class: 'form-control') %>

                          <label class="col-form-label">Team Gym</label>
                          <%= e.text_field(:gym, class: 'form-control') %>

                            <label class="col-form-label">Session</label>
                            <%= s.text_field(:session_name, class: 'form-control') %>

                              <label class="col-form-label">Level</label>
                              <%= e.text_field(:level, class: 'form-control') %>

                                <label class="col-form-label">Product</label>
                                <%= e.select(:product, [["Digital - $80"],["Flash Drive - $100"],["Team Registration - $650"]], {} ,class: 'form-control') %>

                                  <%= e.check_box(:terms, class:'') %>
                                    <%= link_to 'Terms and Conditions', '#', data:{target: '#termsmodal', toggle: 'modal'}%>
                                      <% end %>
                                        <div>
                                          <%= s.submit 'Sign Up', class:'btn btn-primary' %>
                                        </div>
                                        <% end %>

 def new
   @session = Session.new()
   @session.build_event
 end

 def create
   @session = Session.find_or_create_by(session_name: 
   params[:session_name])
   @event = @session               #This is where i'm confused
    @event.new(session_params)
    if @session.save
     flash[:success] = "You have successfully signed up"
    redirect_to signup_path
   else
    render 'signup'
     end
 end

 def edit
   @events = Event.find(params[:format])
   @session = Session.find(@events.session_id)
 end

 def update
   puts params.inspect

  @events = Event.find(params[:event][:id])
  if @events.update_attributes(event_params)
   redirect_to event_path
 else
  render 'edit'
  end
end

Solution

  • First of all you have wrong associations. Model with reference (session_id in your case) always belongs_to something. So you should have belongs_to :session in Event and has_one :event in Session. And to build proper form you should use nested attributes. You can look at example Here. In general form should look like this.

    <%= form_for(@session) do |f| %>
    ...
    <%= f.fields_for :event do |builder| %>
      <%= builder.label :some_field, "Some field" %><br />
      <%= builder.text_field :some_field %><br />
      ...
    <% end %>
    ...
    
    <% end %>
    

    Do not forget to add accepts_nested_attributes_for :event in Session