Forum: Ruby on Rails Help with this syntaxis

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
71e53b54803415f87ef1b898baf8f3ca?d=identicon&s=25 John Smith (terry_wolf)
on 2009-03-09 09:13
I have some doubts when to use this syntaxis in models:

 First, width this code:
 def project_attributes=(project_attributes)
      ...
 end



 And second width this code:
 def add_to_cart(msg = nil)
      ...
 end


 I don't know when should I use this syntaxis in this model methods. Can
someone explain it with small examples. I'll appreciate any help.
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2009-03-09 10:29
(Received via mailing list)
On Mar 9, 8:13 am, John Smith <rails-mailing-l...@andreas-s.net>
wrote:
>  end
>
>  I don't know when should I use this syntaxis in this model methods. Can
> someone explain it with small examples. I'll appreciate any help.

Well at a basic level the first defines a method called
project_attributes= (so that you can do some_object.project_attributes
= something) and the other defines an add_to_cart method with an
optional argument that defaults to nil). Not much more that can be
said without some context.


Fred
71e53b54803415f87ef1b898baf8f3ca?d=identicon&s=25 John Smith (terry_wolf)
on 2009-03-09 11:02
Some more code:

First example:
  Model
  def project_attributes=(project_attributes)
    project_attributes.each do |attributes|
      if attributes[:id].blank?
        projects.build(attributes)
      else
        project = projects.detect { |t| t.id == attributes[:id].to_i }
        project.attributes = attributes
      end
    end
  end

  Controller:
  def new
      ...
      3.times{ @job.projects.build }
  end

  View:
  <div class="project">
    <% fields_for "receta[project_attributes][]", project do
|project_form| %>
  <p>
      project: <%= project_form.text_field :name, :index => nil %>
      ...
  </p>
    <% end %>
  </div>




Second:
   So msg = nil unless I pass a parameter msg with some value. It is
correct?


Thanks a lot.
71e53b54803415f87ef1b898baf8f3ca?d=identicon&s=25 John Smith (terry_wolf)
on 2009-03-09 11:03
The code above has an error, but I can not edit it. Job
has_many:projects. Not consider receta, it's 'job'.
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2009-03-09 14:40
(Received via mailing list)
On 9 Mar 2009, at 10:02, John Smith wrote:
>
> Second:
>   So msg = nil unless I pass a parameter msg with some value. It is
> correct?
>
yes, that's what optional arguments do.

Fred
This topic is locked and can not be replied to.