views:

20

answers:

2

I have two models Station and Broadcast. Broadcast belongs_to Station and has a station_id column.

I don't know how to make new method in BroadcastController to expect the station_id value and how to create a new Broadcast with right station_id in it.

A: 

You actually do specify a station_id for your Broadcast model, such as

script/generate scaffold broadcast name:string station_id:integer ...

so when you add a broadcast record, it will ask you for a station_id.

動靜能量
It's not exactly what i need. I've got index view for Stations and link_to "Add broadcast" in each station, so i need to pass broadcast_id automatically to the new method of broadcast controller.
maxt3r
Don't you mean 'pass the station_id'?
Dave Sims
A: 

I'd recommend against using a link_to here. Using a 'get' action to change/add data on the server is generally frowned upon. Also, I wouldn't use the 'new' action, as it's used by convention in a Rails Restful route to present a form, not actually persist data. All that said, the simple answer to your question is to pass a value through the link_to helper like so:

link_to 'Add broadcast', new_broadcast_path(:station_id => station.id)

...and your 'new' method on BroadcastsController would do:

def new
  @broadcast = BroadCast.new(:station_id => params[:station_id])
  if @broadcast.save
    flash[:notice] = "New broadcast created!"
    redirect :back # or whatever
  else
    # etc.
  end
end

But, again, this is not the right way to do this. What you probably want to do is stay within the Rails (and web) conventions and use a form to create the new broadcast record by way of the 'create' action on the controller. You might place this form next to your stations on the index view which presents a button that points to the correct 'create' action of BroadcastsController, and uses a hidden_field to set the station_id. Something like (EDIT: better use of hidden_field):

<% form_for :broadcast do |f| %>
  <%= f.hidden_field :station_id, :value=> station.id %>
  <%= submit_tag  'Add broadcast' %>
<% end %>

Assuming you've set a restful route in routes.rb for broadcast like:

map.resources :broadcasts

...then your form will automatically point to a 'create' action on BroadcastsController, which you should write to look something like:

def create
  @broadcast = BroadCast.new(params[:broadcast])
  if @broadcast.save
  # etc., etc.
end

The Rails Guides are a good place to get more comfortable with the Rails controller actions. I'd also spend some time looking over the RESTful actions and how they're used in Rails as well.

Dave Sims