<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>kev.in &#187; Models</title>
	<atom:link href="http://kev.in/category/models/feed" rel="self" type="application/rss+xml" />
	<link>http://kev.in</link>
	<description>"It was a musical thing and you were supposed to sing"</description>
	<lastBuildDate>Thu, 13 Nov 2008 09:23:04 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>How to limit users to one vote per IP address</title>
		<link>http://kev.in/2008/01/18/how-to-limit-users-to-one-vote-per-ip-address.html</link>
		<comments>http://kev.in/2008/01/18/how-to-limit-users-to-one-vote-per-ip-address.html#comments</comments>
		<pubDate>Fri, 18 Jan 2008 16:52:52 +0000</pubDate>
		<dc:creator>Kev.in</dc:creator>
				<category><![CDATA[Controllers]]></category>
		<category><![CDATA[Migrations]]></category>
		<category><![CDATA[Models]]></category>

		<guid isPermaLink="false">http://railsauthority.com/tutorial/how-to-limit-users-to-one-vote-per-ip-address</guid>
		<description><![CDATA[A reader Aaron J. writes in response to the short article How to obtain the IP address of the current user:
Do you have any advice on how I can take this a step further? I am looking to limit a given user to one vote per session but I’m not sure how to achieve this. [...]]]></description>
			<content:encoded><![CDATA[<p>A reader <strong>Aaron J.</strong> <a href="/2007/08/26/how-to-obtain-the-ip-address-of-the-current-user.html#comment-6">writes</a> in response to the short article <a href="/2007/08/26/how-to-obtain-the-ip-address-of-the-current-user.html">How to obtain the IP address of the current user</a>:</p>
<blockquote><p>Do you have any advice on how I can take this a step further? I am looking to limit a given user to one vote per session but I’m not sure how to achieve this. I’d appreciate any help you can offer. Thanks for your time.</p></blockquote>
<p>Good question, Aaron. Remember that a session is simply tied to your browser cookie, so if we allow one vote per session, all the user has to do is clear their cookies and then vote again. And again. And again! So I think what you mean is how do we allow only one vote per IP address? To enforce that, we&#8217;ll need to save a list of the IP addresses that have already sent us a vote. And before we record a vote, we need to make sure their IP address isn&#8217;t already on that list. Further, we should remember which poll number they have voted in so we can have more than one poll in our application. We&#8217;re going to need a simple table:</p>
<pre name="code" class="ruby:nocontrols:nogutter"># lib/db/migrate/001_voter_log.rb
create_table :vote_log do |t|
  t.column :poll_id, :integer
  t.column :client_ip, :string
end
</pre>
<p>For simplicity of this example, we&#8217;ll put all of our logic in the controller. (I won&#8217;t show the VoteLog model class because it&#8217;s empty.)</p>
<pre name="code" class="ruby:nocontrols:nogutter">
# RAILS_ROOT/app/controllers/poll_controller.rb
def record_a_vote
  poll_id = params[:poll_id]
  client_ip = request.remote_ip

  unless VoteLog.count(:all, :conditions => ['poll_id = ? AND client_ip = ?', poll_id, client_ip]) == 0
    redirect_to :already_voted
  end

  Poll.find(poll_id).record_vote(params[:candidate]) # Or however you count votes
  VoteLog.create(:poll_id => poll_id, :client_ip => client_ip)
end

def already_voted
  render :text => "You already voted, no cheating!"
end
</pre>
<p>Just keep in mind this approach might not be appropriate in all situations. Due to Network Address Translation (NAT) firewalls, many thousands of people will appear to have the same client_ip. This is particularly true in corporate environments. If that&#8217;s a concern, you&#8217;ll need to go with a full-blown registered-user approach.</p>
<h3>Further Reading</h3>
<p><a href="/tutorial/how-to-obtain-the-ip-address-of-the-current-user">How to obtain the IP address of the current user</a></p>
<h3>Feedback and Article Ideas</h3>
<p>Want to see a topic explored here? <a href="/contact">Send Me a Message</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://kev.in/2008/01/18/how-to-limit-users-to-one-vote-per-ip-address.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>De-tangling attr_reader, attr_writer and attr_accessor from attr_protected &amp; attr_accessible (Part 1)</title>
		<link>http://kev.in/2007/08/27/de-tangling-attr_reader-attr_writer-and-attr_accessor-from-attr_protected-attr_accessible-part-1.html</link>
		<comments>http://kev.in/2007/08/27/de-tangling-attr_reader-attr_writer-and-attr_accessor-from-attr_protected-attr_accessible-part-1.html#comments</comments>
		<pubDate>Tue, 28 Aug 2007 01:00:49 +0000</pubDate>
		<dc:creator>Kev.in</dc:creator>
				<category><![CDATA[Models]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://railsauthority.com/tutorial/de-tangling-attr_reader-attr_writer-and-attr_accessor-from-attr_protected-attr_accessible-part-1</guid>
		<description><![CDATA[What a mess. You have undoubtedly run across these methods sprinkled throughout the Ruby and Rails world. If you&#8217;ve been working with Rails for even a short time, you&#8217;ve probably read a little about security and attr_accessible. But do you really understand what each of them do and when to use them?
I&#8217;m not a fan [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright" src="http://railsauthority.com/wp-content/uploads/274334_6040.jpg" title="Car crash" alt="Car crash" height="107" width="160" />What a mess. You have undoubtedly run across these methods sprinkled throughout the Ruby and Rails world. If you&#8217;ve been working with Rails for even a short time, you&#8217;ve probably read a little about security and <code>attr_accessible</code>. But do you really understand what each of them do and when to use them?<br />
I&#8217;m not a fan of whoever made these methods so closely named, especially because they serve very different purposes: two are specific to Rails (or more accurately, ActiveRecord), while the other three are Ruby core methods. When I have a need for any of them, I still have to really think about which one I actually want to use. Often I still have to glance at the rdocs to be reassured my choice is the right one. So let&#8217;s dive in and figure out what the heck these are supposed to do, and when to use them.</p>
<p><span id="more-114"></span></p>
<h3>Forget Rails, Let&#8217;s Talk Ruby Attributes</h3>
<p>I&#8217;ve noticed a fair number of folks try to write Rails apps without much knowledge of Ruby. That&#8217;s a noble thing to try, but to be a truly effective Rails developer, you&#8217;ll need to be intimately knowledgeable about the Ruby language.</p>
<p>For this reason, and to get our feet wet, we&#8217;ll ignore the Rails methods for a moment and focus on the Ruby, since that&#8217;s the source of three important <code>attr_*</code> methods: <code>attr_accessor</code>, <code>attr_reader</code>, and <code>attr_writer</code>. Put these three methods together in a bucket inside your head, as they are closely related.</p>
<p>Say we have a simple little Ruby class (remember we&#8217;re ignoring Rails at the moment, so this is just a basic Ruby <code>Object</code> class, not an ActiveRecord model).</p>
<p class="code-source">In <span class="filename">address.rb</span>:</p>
<pre name="code" class="ruby">
class Address

   def initialize(line1, line2, city, state, zip)
     @line1 = line1
     @line2 = line2
     @city = city
     @state = state
     @zip = zip
   end

   def to_s
     &quot;#{@line1}\n#{@line2}\n#{@city}, #{@state} #{@zip}&quot;
   end

end</pre>
<p>Our class doesn&#8217;t do much yet, but we can create an <code>Address</code> instance and print it as a string using the <code>to_s</code> method:</p>
<pre name="code" class="ruby:nocontrols:nogutter">
irb(main):001:0&gt; require &apos;address&apos;
=&gt; true
irb(main):002:0&gt; address = Address.new(&quot;Centropy&quot;, &quot;PO Box 1236&quot;, &quot;Santa Clara&quot;, &quot;CA&quot;, &quot;95052&quot;)
=&gt; #&lt;Address:0x85908 @line2=&quot;PO Box 1236&quot; @zip=&quot;95052&quot; @line1=&quot;Centropy&quot; @state=&quot;CA&quot; @city=&quot;Santa Clara&quot;&gt;
irb(main):003:0&gt; puts address.to_s
Centropy
PO Box 1236
Santa Clara, CA 95052
</pre>
<p>What if we want to be able to get each of those attributes separately from the full address, say to print out only the zip code? Trying to print the zip attribute with our current code won&#8217;t work:</p>
<pre name="code" class="ruby:nocontrols:nogutter">
irb(main):004:0&gt; puts address.zip
NoMethodError: undefined method `zip&apos; for #&lt;Address:0x85908&gt;
        from (irb):4
        from :0
</pre>
<p>In order to call <code>address.zip</code>, we need an attribute getter to make the <code>@zip</code> instance variable visible outside the instance. If you&#8217;re from the world of Java you&#8217;re probably intimately familiar with these so-called &#8220;getter&#8221; methods. So, you&#8217;d go and write your &#8220;getter&#8221; method for <code>@zip</code>:</p>
<pre name="code" class="ruby">
class Address

   def initialize(line1, line2, city, state, zip)
     @line1 = line1
     @line2 = line2
     @city = city
     @state = state
     @zip = zip
   end

   def zip
     @zip
   end

   def to_s
     &quot;#{@line1}\n#{@line2}\n#{@city}, #{@state} #{@zip}&quot;
   end

end
</pre>
<p>Okay, only four more methods to go and you can head over to the water cooler for a well-deserved break! (You get paid by the line, after all!) It feels kinda silly, though, since all these methods follow an identical pattern. Since this is such a common pattern, Ruby gives us a little shortcut: anytime you would add an attribute getter as above, you can and should use the handy <code>attr_reader</code> method instead, which effectively creates the attribute getter methods for us behind the scenes, without us having to explicitly define each method in detail. Our new class looks like this:</p>
<pre name="code" class="ruby">
class Address

   def initialize(line1, line2, city, state, zip)
     @line1 = line1
     @line2 = line2
     @city = city
     @state = state
     @zip = zip
   end

   # Note we can give attr_reader multiple attributes,
   # and they are specified as :symbols
   attr_reader :line1, :line2, :city, :state, :zip

   def to_s
     &quot;#{@line1}\n#{@line2}\n#{@city}, #{@state} #{@zip}&quot;
   end

end
</pre>
<p>Now we can grab all of our attributes apart from the full address:</p>
<pre name="code" class="ruby:nocontrols:nogutter">
irb(main):001:0&gt; require &apos;address&apos;
=&gt; true
irb(main):002:0&gt; address = Address.new(&quot;Centropy&quot;, &quot;PO Box 1236&quot;, &quot;Santa Clara&quot;, &quot;CA&quot;, &quot;95052&quot;)
=&gt; #&lt;Address:0x854bc @line2=&quot;PO Box 1236&quot; @zip=&quot;95052&quot; @line1=&quot;Centropy&quot; @state=&quot;CA&quot; @city=&quot;Santa Clara&quot;&gt;
irb(main):003:0&gt; puts address.zip
95052
</pre>
<p>But what about <em>setting</em> the zip code?</p>
<pre name="code" class="ruby:nocontrols:nogutter">
irb(main):004:0&gt; address.zip=&apos;95050&apos;
NoMethodError: undefined method `zip=&apos; for #&lt;Address:0x854bc&gt;
        from (irb):4
        from :0
</pre>
<p>Nope, doesn&#8217;t work. Maybe that&#8217;s what you want: if an attribute should not be settable after the object is instantiated, you wouldn&#8217;t want the ability to set the value of an attribute like this. (If you ever hear the term &#8220;immutable&#8221;, that is what we&#8217;re talking about here: Address instances are currently immutable because they can not be &#8220;mutated,&#8221; or changed, after instantiation.) But if you do want to set your attribute values, you&#8217;ll need to create a way for code outside the instance to change the value of that somewhat elusive <code>@zip</code> instance variable. Again, if you are coming from Java programming, you&#8217;d attempt to write a &#8220;setter&#8221; method here:</p>
<pre name="code" class="ruby">
class Address

   def initialize(line1, line2, city, state, zip)
     @line1 = line1
     @line2 = line2
     @city = city
     @state = state
     @zip = zip
   end

   # Note we can give attr_reader multiple attributes,
   # and they are specified as :symbols
   attr_reader :line1, :line2, :city, :state, :zip

   # Allow setting the instance attribute to a new value
   def zip=(new_zip)
     @zip = new_zip
   end

   def to_s
     &quot;#{@line1}\n#{@line2}\n#{@city}, #{@state} #{@zip}&quot;
   end

end
</pre>
<p>But, if you&#8217;re starting to hear harp music right now, you might be thinking that Ruby might give us an equally simple, declarative way to make attribute setter methods as it did for getters. Lo and behold, <code>attr_writer</code> comes to the rescue:</p>
<pre name="code" class="ruby">
class Address

   def initialize(line1, line2, city, state, zip)
     @line1 = line1
     @line2 = line2
     @city = city
     @state = state
     @zip = zip
   end

   # Note we can give attr_reader multiple attributes,
   # and they are specified as :symbols
   attr_reader :line1, :line2, :city, :state, :zip

   # Those attributes are writable, too
   attr_writer :line1, :line2, :city, :state, :zip

   def to_s
     &quot;#{@line1}\n#{@line2}\n#{@city}, #{@state} #{@zip}&quot;
   end

end</pre>
<p>And now we can set or get any attribute value:</p>
<pre name="code" class="ruby:nocontrols:nogutter">
irb(main):001:0&gt; require &apos;address&apos;
=&gt; true
irb(main):002:0&gt; address = Address.new(&quot;Centropy&quot;, &quot;PO Box 1236&quot;, &quot;Santa Clara&quot;, &quot;CA&quot;, &quot;95052&quot;)
=&gt; #&lt;Address:0x8519c @line2=&quot;PO Box 1236&quot; @zip=&quot;95052&quot; @line1=&quot;Centropy&quot; @state=&quot;CA&quot; @city=&quot;Santa Clara&quot;&gt;
irb(main):003:0&gt; address.zip=&apos;95050&apos;
=&gt; &quot;95050&quot;
irb(main):004:0&gt; puts address.zip
95050
</pre>
<p>Now, you might think we&#8217;re in good shape: we&#8217;ve consolidated what would have been ten different method definitions into a two lines of declarative, readable code. Not so fast! There&#8217;s a bit of redundancy in those two lines, isn&#8217;t there? Specifying all your fields in two places is clearly less maintainable than if we could tell Ruby &#8220;we want getters <em>and</em> setters for this list of attributes.&#8221; It might not be a big deal for our little Address class, but when you have hundreds or thousands of classes that you haven&#8217;t looked at in a year, every extraneous line matters.</p>
<p>Again, this is such a common scenario in programming that Ruby offers the third attribute method, <code>attr_accessor</code>, which does exactly what two separate calls to <code>attr_reader</code> and <code>attr_writer</code> would do.</p>
<p>So, let&#8217;s get rid of that repetition now:</p>
<pre name="code" class="ruby">
class Address

   def initialize(line1, line2, city, state, zip)
     @line1 = line1
     @line2 = line2
     @city = city
     @state = state
     @zip = zip
   end

   # attr_accessor can take multiple attributes like the others,
   # and they are specified as :symbols
   attr_accessor :line1, :line2, :city, :state, :zip

   def to_s
     &quot;#{@line1}\n#{@line2}\n#{@city}, #{@state} #{@zip}&quot;
   end

end</pre>
<p>And this works <em>exactly</em> like the previous example:</p>
<pre name="code" class="ruby:nocontrols:nogutter">
irb(main):001:0&gt; require &apos;address&apos;
=&gt; true
irb(main):002:0&gt; address = Address.new(&quot;Centropy&quot;, &quot;PO Box 1236&quot;, &quot;Santa Clara&quot;, &quot;CA&quot;, &quot;95052&quot;)
=&gt; #&lt;Address:0x8519c @line2=&quot;PO Box 1236&quot; @zip=&quot;95052&quot; @line1=&quot;Centropy&quot; @state=&quot;CA&quot; @city=&quot;Santa Clara&quot;&gt;
irb(main):003:0&gt; address.zip=&apos;95050&apos;
=&gt; &quot;95050&quot;
irb(main):004:0&gt; puts address.zip
95050
</pre>
<p>Hopefully this clarifies what these three methods are for. Next time, we&#8217;ll explore the similarly-named-but-entirely-different-purposed <code>attr_protected</code> and <code>attr_accessible</code> methods brought to us by Rails&#8217; ActiveRecord models.</p>
<h3>Further Reading</h3>
<p>The <code>attr_accessor</code>, <code>attr_reader</code>, and <code>attr_writer</code> methods are fairly well documented in the <a href="http://corelib.rubyonrails.org/classes/Module.html#M000794">Ruby core rdocs</a>.</p>
<h3>Feedback and Article Ideas</h3>
<p>Want to see a topic explored here? <a href="/contact">Send Me a Message</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://kev.in/2007/08/27/de-tangling-attr_reader-attr_writer-and-attr_accessor-from-attr_protected-attr_accessible-part-1.html/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
