2

So I'm trying to set a name attribute of organizations and create a new organization or choose from a previously existing organization from the same form.

I've tried to follow Ryan Bates' railscast on the topic here: http://railscasts.com/episodes/57-create-model-through-text-field

I have also tried numerous solutions from stack. However, I can't quite seem to get it to run (that and I have a validation that does not recognize the virtual attribute I'm using)

so my organizations model:

class Organization < ActiveRecord::Base
  has_many :materials
  has_many :users
  has_and_belongs_to_many :causes
  has_and_belongs_to_many :schools, :join_table => 'organizations_schools'
####The following line has been edited ####
  attr_accessible :name, :unlogged_books_num, :id, :new_organization_name
  attr_accessor :new_organization_name
  before_validation :create_org_from_name

  validates_presence_of :name

  def self.assign_school_to_organization(org, school)
    orgschool = OrganizationsSchool.create(:organization_id=> org.id, :school_id=> school[0])
  end

 def create_org_from_name
   create_organization(:name=>new_organization_name) unless new_organization_name.blank?
 end
end

I have also tried the create_org_from_name as the following:

 def create_org_from_name
   self.name = new_organization_name
 end

And this does not change the name to the organization name before validating or saving the instance. I have also tried to change the before_save to before_validation, and that has not worked

My controller for organization (I also tried to change this in create)

def create
   respond_to do |format|
      @organization = Organization.new(params[:organization])
      @organization.name = @organization.new_organization_name unless @organization.new_organization_name.blank?
      if @organization.save
        @school = params[:school]
        Organization.assign_school_to_organization(@organization, @school)     
        format.html { redirect_to @organization, notice: 'Organization was successfully created.' }
        format.json { render json: @organization, status: :created, location: @organization }
      else
        format.html { render action: "new" }
        format.json { render json: @organization.errors, status: :unprocessable_entity }
      end
    end
  end

And finally, I have what my form is doing currently:

<%= form_for(@organization) do |f| %>
  <% if @organization.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@organization.errors.count, "error") %> prohibited this organization from being saved:</h2>

      <ul>
      <% @organization.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <% @schools = School.all %>
  <% @organizations = Organization.all %>
  <div class="field">
      <%= f.label 'Organization Name' %><br />
      <%= f.collection_select(:name, @organizations, :name, :name, :prompt=>"Existing Organization") %>
      Or Create New
      <%= f.text_field :new_organization_name %>
    </div>
    <div class="field">
      <%= f.label :unlogged_books_num %><br />
      <%= f.number_field :unlogged_books_num %>
    </div>
    <div class="field">
      <%= f.label 'School' %><br />
      <% school_id = nil %>
      <%= collection_select(:school, school_id, @schools, :id, :name) %>  
    </div>
    <div class="actions">
      <%= f.submit %>
    </div>
  <% end %>

==================================EDIT============================================ So currently, when I try to make an organization with something only written in the virtual text field, My log tells me the following:

Processing by OrganizationsController#create as HTML
  Parameters: {"utf8"=>"✓",    "authenticity_token"=>"igoefz8Rwm/RHrHLTXQnG48ygTGLydZrzP4gEJOPbF0=", "organization"=>  {"name"=>"", "new_organization_name"=>"Virtual Organization", "unlogged_books_num"=>""},   "school"=>["1"], "commit"=>"Create Organization"}
  Rendered organizations/_form.html.erb (7.1ms)
  Rendered organizations/new.html.erb within layouts/application (8.0ms)
Completed 200 OK in 17ms (Views: 12.2ms | ActiveRecord: 1.0ms)

================================EDIT 2============================================ So this is what I get from the rails console if I try to create a new organization running this command: Organization.create(:new_organization_name=>"Virtual Organization", :unlogged_books_num=>"3")

irb(main):001:0> Organization.create(:new_organization_name=>"Virtual Organization",    :unlogged_books_num=>"3")
   (0.1ms)  BEGIN
   (0.1ms)  ROLLBACK
=> #<Organization id: nil, name: nil, unlogged_books_num: 3, created_at: nil, updated_at: nil>

If the function of create_org_from_name is self.name = new_organization_name, then the result of the same command from the console is blank:

irb(main):002:1> Organization.create(:new_organization_name=>"Virtual Organization", :unlogged_books_num=>"3")
irb(main):003:1> 
  • Can you elaborate on "doesn't work"? Does it give an error message? Does the select work but not the new fill-in name? – lurker Jun 13 '13 at 02:07
  • The result from submitting the form will either be to delete the virtual variable contents if they are entered and display an error that there must be a name before the form can be saved, OR if I eliminate the validation of name, it does not put any name into the organizations table, and I'm stuck with an empty organization name in my database – CimmerianMuse Jun 13 '13 at 02:29
  • I suspect the validation is occurring before the `before_save`. Perhaps try `before_validation :create_org_from_name`. – lurker Jun 13 '13 at 11:19
  • mbratch, I already tried that, and it still would not store the correct value in the database. It still tells me that the name cannot be blank. I have also tried to make the function for `:create_org_from_name` look as such: `self.name == new_organization_name unless new_organization_name.blank?` and it still says that the name cannot be blank, and the form deletes what was written in the `new_organization_name` field without saving any information – CimmerianMuse Jun 13 '13 at 16:11
  • If you look at the verbose spew from the rails server at the console or in the log, when it hits the `create` in the controller, does the `new_organization_name` show up in the dump of the parameter hash? – lurker Jun 13 '13 at 16:18
  • My log from trying to create a new book is now underneath the edit section of my post. The `new_organization_name` shows up, but the name does not in either way I write the `:create_org_from_name` function – CimmerianMuse Jun 13 '13 at 16:53
  • I would go into `rails console`, do a `new` with parameters by hand, and put some debug statements in to see where it's going awry. – lurker Jun 13 '13 at 20:07
  • How would you recommend doing that? I am finding it difficult because I am creating an organization that populates other tables based on the create function in the controller (how would I pass in the parameters that the form does in the console so that this works?) – CimmerianMuse Jun 13 '13 at 20:09
  • According to the information you provided (log and the controller), your log shows a very simple set of parameters for the params hash being passed to `Organization.new`. You would mimic what you're controller is doing, perhaps not manually assigning `name` yet (as that shouldn't be necessary). Check `Organization` attributes. – lurker Jun 13 '13 at 20:16
  • Edited again. Is that what you'd meant for me to do? – CimmerianMuse Jun 13 '13 at 22:46
  • That's exactly what I was looking for. But I'm at a loss why it's failing. You didn't say whether using the select (the alternate case) on your form works. Does it? – lurker Jun 14 '13 at 11:09
  • If you're asking if the select for the schools works, then yes it does. It is just the organizations that are having trouble because I have the create new or choose from existing. If you are wondering what happens when I change the create_org_from_name using different code, I had that posted below the first – CimmerianMuse Jun 14 '13 at 15:05
  • Nope, I was asking about organization. You have two choices on your form for organization: add a new made-up name, or select from a list of existing names. I'm asking of the select from existing name works. – lurker Jun 14 '13 at 15:43
  • oh! Yes it does if I select it from the previously existing choices. If I have `:create_org_from_name` create rather than change the value, it sets the organization name properly. If `:create_org_from_name` is `self.name = new_organization_name`, then it does not. It stores a blank string for the name. – CimmerianMuse Jun 14 '13 at 16:00
  • `:create_org_from_name` should, I believe, have in it `self.name = new_organization_name if not new_organization_name.blank?` (as you had at one time) which should work if you choose the organization from the select. Doing a "create" from within the before_validation method isn't correct (even though it may sometimes give results you like). I'm still not sure why the manual `create` from the rails console did nothing. Right after that case in the console, you could capture the create (my_org = Organization.create( :new_organization_name => 'foo'...)) then check `my_org.new_organization_name`. – lurker Jun 14 '13 at 16:14
  • Oh my goodness. changing the function to `self.name = new_organization_name if not new_organization_name.blank?` worked PERFECTLY (I actually did not have it as `if not`. I think I had tried `unless`). I can't believe it was something so silly as that. Thank you so much. If you'd like to post that as an answer, I'll choose your answer. Thanks SO much for all of your detailed help – CimmerianMuse Jun 14 '13 at 16:42
  • I put it into the answer, where it's final resting place should be. If you could mark it as a satisfactory answer, that would be great. :) – lurker Jun 14 '13 at 21:02

1 Answers1

0

You need:

before_validation :create_org_from_name

and

def create_org_from_name
  self.name = new_organization_name if not new_organization_name.blank?
end

You don't want to do a create in your before_validation method.

lurker
  • 56,987
  • 9
  • 69
  • 103