davidicus
davidicus

Reputation: 649

Placing data from associated table in view

I have a class called Imprintable that contains this

class Imprintable < ActiveRecord::Base
  has_one :brand
  # ...

I also have a class called Style that contains the following:

class Style < ActiveRecord::Base
  belongs_to :imprintable
  # ...

My schema for Styles contains a foreign key to the imprintable table in the form of an integer called imprintable_id

I'm trying to display an attribute from the Style table called catalog_no in a view to edit information about an imprintable. I know what I have is wrong because style doesn't exist as a member of the imprintable table, but I'm not sure how to access the name of the catalog_no from the corresponding entry in the styles table. HTML is like this:

<!-- language: HTML -->
<div class="box-info">
  <%= render partial: 'shared/modal_errors', locals: {object: imprintable} %>
    <%= form_for(imprintable) do |f| %>
      <div id="horizontal-form" class="collapse in">
      <!-- Lots of HTML.. -->

      <div class="form-group">
        <%= f.label :style.catalog_no, class: 'col-sm-2 control-label' %>
        <div class="col-sm-10">
          <%= f.text_field :style.catalog_no, class: 'form-control' %>
          <!-- Problem is on the above line!! -->
          <p class="help-block">The catalog number of the imprintable
        </div>
      </div>
    </div>
  <% end %>
</div>

Thanks for your time!

Upvotes: 0

Views: 40

Answers (1)

rails_id
rails_id

Reputation: 8220

You should use nested form

Model Imprintable looks like this :

class Imprintable < ActiveRecord::Base
  has_one :brand
  accepts_nested_attributes_for :style
end

In controller edit action

def edit
  @imprintable = Imprintable.find(params[:id]) 
end

In the view file edit.html.erb looks like

<div class="box-info">
  <%= render partial: 'shared/modal_errors', locals: {object: imprintable} %>
    <%= form_for(@imprintable) do |f| %>
      <div id="horizontal-form" class="collapse in">
       <%= f.fields_for :style do |d| %>
      <div class="form-group">
        <%= d.label :catalog_no, class: 'col-sm-2 control-label' %>
        <div class="col-sm-10">
          <%= d.text_field :catalog_no, class: 'form-control' %>
          <p class="help-block">The catalog number of the imprintable
        </div>
      </div>
       <% end %>
    </div>
  <% end %>
</div>

If you're using rails 4, don't forget add style_attibutes to impritable_params method

private
  def impritable_params
    ## params.require(:your_model).permit(:fields_of_model, association_model_attributes: [:fields_of_association_models])
    params.require(:imprintable).permit(style_attributes: [:id, :catalog_no])
  end
end

Upvotes: 1

Related Questions