Jump to content

The ultimate community for Ruby on Rails developers.


Photo

Passing parameter from view to controler

passing parameters

  • Please log in to reply
1 reply to this topic

#1 xantippe

xantippe

    Passenger

  • Members
  • 1 posts

Posted 28 February 2014 - 11:19 PM

Hello everybody. I am new to Ruby on Rails and I have one question because I still haven't figured that out. 

 

I am trying to pass additional parameter from view to controller. Below is the view for creating new quote which contains some text, author and a book. The question is, how to pass tags for that quote to the controller.

<%= form_for(@quote) do |f| %>
  <% if @quote.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@quote.errors.count, "error") %> </h2>
      <ul>
      <% @quote.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.text_area :body, :rows => 3, :cols => 130 %>
  </div>
  <div class="field">
    <%= f.label :author %><br />
    <%= f.text_field :author %>
  </div>
  <div class="field">
    <%= f.label :book %><br />
    <%= f.text_field :book %>
  </div>

 
  <div class="field">
	<%= f.text_area :tags, :rows => 1, :cols => 130 %>
  </div>



  <div class="actions">
    <%= f.submit "Create" %>
  </div>
<% end %>

And Quotes Controller (method Create):

def create
    
    @quote = Quote.new(params[:quote])

    
    tags = params[:tags]
    tags = tags.gsub(/\s+/, "")
    tags = tags.split(",")
    tags.each do |t|
        new_tag = Tag.create(:body => t)
        @quote.tags << new_tag
    end
        
    
    
    respond_to do |format|
      if @quote.save
        flash[:notice] = 'Success.'
        format.html { redirect_to(@quote) }
        format.xml  { render :xml => @quote, :status => :created, :location => @quote }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @quote.errors, :status => :unprocessable_entity }
      end
    end
  end

For this I get the following error:

NoMethodError in QuotesController#create

undefined method `each' for "vdfvddbdg, vevereb":String

 

Parameters:

{"utf8"=>"✓",
"authenticity_token"=>"ZxDCs36v3+O76ypAHlFQdny56447XmLumK214j12ps0=",
"quote"=>{"body"=>"cdsdv",
"author"=>"vdvdf",
"book"=>"vfdvdbd",
"tags"=>"vdfvddbdg,
vevereb"},
"commit"=>"Create"}

 

 

but I'm not sure what is going on. Any help is welcome.



#2 danielhanke

danielhanke

    Signalman

  • Members
  • 12 posts
  • LocationCologne, Germany

Posted 02 March 2014 - 05:45 PM

Hi xantippe,

 

params[:tags] is not given. params[:quote][:tags] however is.

 

in general, the controller should not do this job. it should control the flow here, not the details of persistence. 

 

i recommend you to let the quote-model handle the tags-separation here.


  • himanshu339 likes this




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users