views:

155

answers:

1

I have the following. Each article has a title and a body and also up to three urls. I would want to store the urls in a different table. Therefore in my form, i've a field for the urls. However they are not working, only the article fields get entered into the database. how should i specify them? Could any kind soul help me out with this?

class Article
  include DataMapper::Resource

  property :id,     Serial
  property :title,  String
  property :body,   Text

  has n, :urls, through => Resource
end

class Url
  include DataMapper::Resource

  property :id,     Serial
  property :url_01,    String
  property :url_02,    String
  property :url_03,    String

  belongs_to :article
end

post '/create' do
  @article = Article.new(params[:article])
  if @article.save
    redirect "/articles"
  else
    redirect "/articles/new"
  end
end

--------------------------------------
<form action="/create" method="post">
  <p>
    <label>Article Title</label>
    <input type="text" name="article[title]">
  </p>
  <p>
    <label>Article Body</label>
    <input type="text" name="article[body]">
  </p>
  <p>
    <label>Url</label>
    <input type="text" name="article[url_01]">
  </p>

  <p>
    <input type="submit">
  </p>
+1  A: 

I believe that

, through => Resource

is only needed if you are doing a many-to-many relationship. A one-to-many, which I think is what you want, does not require that. Check out the post and comment relationship shown on the associations page.

EDIT for comment:

If I were you, I would name my form fields normally and construct the database object manually, for example:

<form action="/create" method="post">
  <p>
    <label>Article Title</label>
    <input type="text" name="title">
  </p>
  <p>
    <label>Article Body</label>
    <input type="text" name="body">
  </p>
  <p>
    <label>Url</label>
    <input type="text" name="url">
  </p>

  <p>
    <input type="submit">
  </p>

and then:

post '/create' do
  @article = Article.new(
      :title      => params[:title],
      :body       => params[:body]
  )
  @url = url.new(
      url_01 => params[:url]
  )
  @article.url = @url

  if @article.save
    redirect "/articles"
  else
    redirect "/articles/new"
  end
end
kersny
what about the form? <input type="text" name="article[url_01]"> does not work, the input does not get saved into database.
little.programmer
In the above example, he just has "url" as the field in the html form. If you are showing all three, then you would need to update the url.new constructor with all three from the html form.
Ian